HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Splitting a List

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listsplittingstackoverflow

Problem

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 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.

Solution

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)

Code Snippets

split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' list value cmp = filter (\x -> compare x value == cmp) list
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]
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.