无法将预期类型“Bool”与实际类型“a -> Bool”相匹配

Couldn't match expected type ‘Bool’ with actual type ‘a -> Bool’

我想编写一个 returns 列表最长前缀的函数,其中将函数应用于该前缀中的每个项目会生成一个严格升序的列表。

例如:

longestAscendingPrefix (`mod` 5) [1..10] == [1,2,3,4]

longestAscendingPrefix odd [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)

此代码片段产生了标题中的错误消息。看来问题出在那个 lambda 函数中。

takeWhile 的类型为 takeWhile :: (a -> Bool) -> [a] -> [a]。因此,第一个参数是一个将列表的 元素 映射到 Bool 的函数。您的 lambda 表达式的类型为 Ord b => a -> a -> Bool,这没有多大意义。

您可以使用显式递归:

longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix f = go
    where go [] = []
          go [x] = …
          go (x1:x2:xs) = …

需要填写的 部分最后一个对 go.

进行递归调用