Haskell 关于模式匹配的问题
我正在尝试编写一个函数,该函数接受一个列表,如果按排序顺序返回 true,如果不是按排序顺序则返回 false:
到目前为止,我所拥有的是:
myordered [] = True
myordered [x] = True
myordered list1
| (head list1) <= (head (tail list1)) = myordered(tail list1)
| otherwise = False
根据我们的分配,所有头和尾操作应写为“ x:xs”类型语法。
我对带有警卫的部分的翻译是:
myordered y:x:xs
| (y) <= (x) = myordered(xs)
| otherwise = False
本质上这个问题可以归结为: 如何用“x:xs”类型语法表达 (head (tail list1)) ?
干杯, -紫谷
I'm trying to write a function that takes in a list and returns true if it is in sorted order and false if not:
So far what I have is:
myordered [] = True
myordered [x] = True
myordered list1
| (head list1) <= (head (tail list1)) = myordered(tail list1)
| otherwise = False
Based on our assignment, all head and tail operations should be written down as "x:xs" type syntax.
the translation I come up with for the section with a guard is:
myordered y:x:xs
| (y) <= (x) = myordered(xs)
| otherwise = False
Essentially this question boils down to:
How do you express the (head (tail list1)) in "x:xs" type syntax?
Cheers,
-Zigu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的模式几乎是正确的,您只需要用括号将其括起来:
另请注意,在
y <= 中不需要用括号将
y
和x
括起来x。另外,您的第二个版本中存在语义错误:
myordered(xs)
这里xs
指的是 tail 的尾部,但您想要整个尾部,所以您应该这样做myordered (x:xs)
或者:其中表示:
xs
是该列表的尾部,x
是该尾部的头部,而_
(被忽略)是尾部的尾部。Your pattern is almost correct, you just need to surround it with parentheses:
Also note that there's no need to surround
y
andx
with parentheses iny <= x
.Also there's a semantic mistake in your second version:
myordered(xs)
herexs
refers to the tail of tail, but you want the whole tail, so you should domyordered (x:xs)
or alternatively:Which says:
xs
is the tail of that list,x
is the head of that tail, and_
(which is ignored) is the tail of the tail.借助
Data.List
中提供的zipWith
函数的另一种方法来实现此目的怎么样?zipWith
函数接受两个列表并应用一个函数。这里它会根据条件返回一个布尔数组。and
接受布尔值列表,仅当列表中的所有值均为 True 时才返回 TrueHow about another way to do this with the help of
zipWith
function available inData.List
zipWith
function takes two list and apply a function. Here it will return an array of boolean according to the condition .and
takes a list of boolean values and returns True only if all the values in the list are True怎么样:
哦,只是为了好玩
How about
Oh, and just for fun: