找到给定条件的列表的最后一个元素
我正在尝试编写一个函数,该函数鉴于所有ints都大于100
isLeast100All :: [Int] -> [Int]
isLeast100All list = filter (>100) list
lastList :: [Integer] -> Integer
lastList list' = case list' of
isLeast100All list
| list == [] -> 0
| list == [x] -> x
| list == [x:xs] -> lastList xs
。 isleast100all“
我觉得这里很简单,但我不确定它是什么。我正在根据以下定义来基于我的最后列表函数:
lastList :: [Integer] -> Integer
lastList x = case x of
[] -> 0
[x] -> x
x:xs -> lastList xs
I'm trying to write a function that finds the last element of a list of Ints given that all the Ints are greater than 100. This is the code I have written so far:
isLeast100All :: [Int] -> [Int]
isLeast100All list = filter (>100) list
lastList :: [Integer] -> Integer
lastList list' = case list' of
isLeast100All list
| list == [] -> 0
| list == [x] -> x
| list == [x:xs] -> lastList xs
which gives me the error: "Parse error in pattern: isLeast100All"
I feel like there's something simple that I'm missing here but I'm not sure what it is. I'm basing my lastList function off the following definition:
lastList :: [Integer] -> Integer
lastList x = case x of
[] -> 0
[x] -> x
x:xs -> lastList xs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要修复您的类型并使用
过滤
而不是MAP
iSleast100All
:或仅:或仅:
You need to fix your types and use
filter
instead ofmap
forisLeast100All
:Or just:
您对
lastList
的定义有两个问题。您已经混淆了list
和列表'
, [x:xs] 应该是(x:xs)
,并且您正在混合谓词后卫和表达的案例。这是您可以使用谓词后卫来定义它的一种方法:
是另一种使用情况...
这 但是我的目标是使它们与您的代码尽可能相似。
Guru Stron的答案提供了更简单的选择。
There are a couple of problems with your definition of
lastList
. You have confusedlist
andlist'
,[x:xs]
should be(x:xs)
, and you're mixing predicate guards and case ... of expression.Here's one way you can define it using predicate guards:
Here's another using case ... of:
This latter one is needlessly inefficient because the filtering function
isLeast100All
is applied to the entire remaining list at every level of recursion but I aimed to make these as similar to your code as possible.The answer by Guru Stron gives simpler alternatives.