[英]Sort a list in haskell according to a predicate
I am trying to learn Haskell and I've come into issues trying to complete an example problem. 我正在尝试学习Haskell,并且在尝试完成示例问题时遇到了一些问题。 The problem is to sort a list in Haskell according to a given predicate ie the type is
问题是根据给定的谓词在Haskell中对列表进行排序,即类型为
sort :: (a -> a -> Bool) -> [a] -> [a]
The code I have so far is : 到目前为止,我的代码是:
sort _ [] = []
sort f (x:xs) =
let
smaller = sort f (filter (f x) xs)
bigger = sort f (filter (f x) xs) --error is on this line
in smaller ++ [x] ++ bigger
The code not working correctly in the sense im not sure how to take the opposite of the function. 从某种意义上讲,代码无法正常工作,我不确定如何采取与该功能相反的方式。 for example if it were an ordinary sort function I would use
smaller = quicksort (filter (<=x) xs)
and bigger = quicksort (filter (>x) xs)
this would then break up the list according to that predicate but how do I do this with a higher order predicate? 例如,如果它是一个普通的排序函数,我将使用
smaller = quicksort (filter (<=x) xs)
和bigger = quicksort (filter (>x) xs)
,然后将根据该谓词分解列表,但该怎么做我使用更高阶的谓词来执行此操作吗?
You just need to use the not
function to invert your boolean: 您只需要使用
not
函数来反转布尔值:
not :: Bool -> Bool
f :: a -> a -> Bool
f x :: a -> Bool
not . f x :: a -> Bool
And you'd use it as 你会用它作为
sort _ [] = []
sort f (x:xs) =
let smaller = sort f (filter (f x) xs)
bigger = sort f (filter (not . f x) xs)
in smaller ++ [x] ++ bigger
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.