我想编写一个返回列表的最长前缀的函数,其中将函数应用于该前缀中的每个项目会生成一个严格升序的列表。
例如:
最长的升序前缀 (`mod` 5) [1..10] == [1,2,3,4]
最长升序前缀奇数 [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)
Run Code Online (Sandbox Code Playgroud)
此代码片段产生标题中的错误消息。问题似乎出在 lambda 函数上。
takeWhile有类型takeWhile :: (a -> Bool) -> [a] -> [a]. 因此,第一个参数是将列表的元素映射到 a 的函数Bool。您的 lambda 表达式具有 type Ord b => a -> a -> Bool,这没有多大意义。
您可以使用显式递归:
\nlongestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]\nlongestAscendingPrefix f = go\n where go [] = []\n go [x] = …\n go (x1:x2:xs) = …Run Code Online (Sandbox Code Playgroud)\n您需要填写\xe2\x80\xa6最后一个递归调用的部分go。