[英]Couldn't match expected type ‘Bool’ with actual type ‘a -> Bool’
I want to write a function that returns the longest prefix of a list, where applying a function to every item in that prefix produces a strictly ascending list.我想编写一个 function 来返回列表的最长前缀,其中将 function 应用于该前缀中的每个项目会产生一个严格升序的列表。
For example:例如:
longestAscendingPrefix (`mod` 5) [1..10] == [1,2,3,4]
最长升序前缀 (`mod` 5) [1..10] == [1,2,3,4]
longestAscendingPrefix odd [1,4,2,6,8,9,3,2,1] == [1]
最长升序前缀奇数 [1,4,2,6,8,9,3,2,1] == [1]
longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix _ [] = []
longestAscendingPrefix f (x:xs) = takeWhile (\y z -> f y <= f z) (x:xs)
This code snippet produces the error message in the title.此代码片段在标题中生成错误消息。 It seems the problem lies within that lambda function.
似乎问题在于 lambda function。
takeWhile
has type takeWhile:: (a -> Bool) -> [a] -> [a]
. takeWhile
的类型为takeWhile:: (a -> Bool) -> [a] -> [a]
。 The first parameter is thus a function that maps an element of the list to a Bool
.因此,第一个参数是将列表的元素映射到
Bool
的 function 。 Your lambda expression has type Ord b => a -> a -> Bool
, which does not make much sense.您的 lambda 表达式的类型为
Ord b => a -> a -> Bool
,这没有多大意义。
You can work with explicit recursion with:您可以通过以下方式使用显式递归:
longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix f = go
where go [] = []
go [x] = …
go (x1:x2:xs) = …
where you need to fill in the …
parts the last one makes a recursive call to go
.您需要在其中填写
…
部分最后一个对go
进行递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.