3
\$\begingroup\$

I wrote the following split function. It takes a list, an element and an Ordering (LT, GT, EQ). For LT, the list will filter out all items that are >= the element argument.

split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' [] _ _ = []
split' (x:xs) a LT
  | x < a     = x : split' xs a LT
  | otherwise = split' xs a LT 
split' (x:xs) a GT
  | x > a     = x : split' xs a GT
  | otherwise = split' xs a GT
-- non-exhaustive, unacceptable

Example:

*Main> split' [1,2,3] 2 LT
[1]

Note that this function can result in an exception if the Ordering argument is EQ. Of course this is terrible.

However, please review the above code, offering suggestions on how to improve it.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Your split' could be simplified using filter.

split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' list value cmp = filter (\x -> compare x value == cmp) list

I think that the order of arguments to split' is awkward. I would suggest that the reverse order is more natural.

split :: (Ord a) => Ordering -> a -> [a] -> [a]
split cmp value list = filter (\x -> compare x value == cmp) list

*Main> split LT 2 [1, 2, 3]
[1]

Then you could also define split in a curried form:

split :: (Ord a) => Ordering -> a -> ([a] -> [a])
split cmp value = filter (\x -> compare x value == cmp)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.