patternMinor
Splitting a List
Viewed 0 times
listsplittingstackoverflow
Problem
I wrote the following
Example:
Note that this function can result in an exception if the
However, please review the above code, offering suggestions on how to improve it.
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 GT
| otherwise = split' xs a GT
-- non-exhaustive, unacceptableExample:
*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.
Solution
Your
I think that the order of arguments to
Then you could also define
split' could be simplified using filter.split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' list value cmp = filter (\x -> compare x value == cmp) listI 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)Code Snippets
split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' list value cmp = filter (\x -> compare x value == cmp) listsplit :: (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]split :: (Ord a) => Ordering -> a -> ([a] -> [a])
split cmp value = filter (\x -> compare x value == cmp)Context
StackExchange Code Review Q#46693, answer score: 3
Revisions (0)
No revisions yet.