简体   繁体   English

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

[英]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.

相关问题 Haskell:无法将预期类型“[a0]”与实际类型“([char], [int])”相匹配 - Haskell: Couldn't match expected type '[a0]' with actual type '([char], [int])' Haskell错误 - 无法匹配预期类型 - Haskell Error - Couldn't match expected type Haskell无法匹配预期的类型,奇怪的行为 - Haskell couldn't match expected type, Weird behaviour 以 bool 数据类型打开字典 - opening dictionaries in bool data type 如何在 Swift switch 语句中解决“&#39;Bool&#39; 类型的表达式模式无法匹配&#39;Double&#39; 类型的值” - How to solve "Expression pattern of type 'Bool' cannot match values of type 'Double'" in Swift switch statement 使用字符串更改Bool类型的值 - Change value of type Bool by using string 结构错误表达式必须具有布尔类型 - struct error expression must have bool type 错误:“无法将类型&#39;int&#39;隐式转换为&#39;bool&#39;” - Error: “cannot implicitly convert type 'int' to 'bool' ” 为什么是`谓词<t> ` 不匹配 `Func<t,bool> `?</t,bool></t> - Why a `Predicate<T>` doesn't match a `Func<T,bool>`? 当我调用带有空括号的 bool 类型单个参数的函数时,bool 参数的值是多少? - When I call a function with single argument of type bool with empty parentheses, what is the value of a bool parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM