问题
How would I use the greater or less than sign as a variable so that when I enter Main> mySort (<) [1,5,3,6,4,1,3,3,2]
or Main> mySort (>) [1,5,3,6,4,1,3,3,2]
it will sort the list from highest to lowest or lowest to highest depending on which sign I chose to enter?
回答1:
You can just pass (<)
in and use it compare each value.
A similar function
mySort :: (a -> a -> Ordering) -- Comparator function
-> [a]
-> [a]
And Haskell is so smart that this already exists as sortBy
. This lets you pass in a function returning an Ordering
which is just
data Ordering = LT | EQ | GT deriving(...)
But you have functions a -> a -> Bool
so you need to make this into an ordering and then you can use it with sortBy
.
wrap f a b | not $ f a b || f b a = EQ
| f a b = LT
| otherwise = GT
Now you can use this to wrap (<)
and (>)
to lift it to be used with sortBy
mySort :: (a -> a -> Bool) -> [a] -> [a]
mySort = sortBy . wrap
回答2:
There already is a function in Data.List that does very similar thing to what you want, it is called sortBy.
However if you really want to implement it you could use sortBy like this:
mySort cop ls = sortBy (\a b -> if (cop a b) then LT else GT) ls
or even shorter (using eta reduction):
mySort cop = sortBy (\a b -> if (cop a b) then LT else GT)
来源:https://stackoverflow.com/questions/16182156/how-to-use-as-a-variable