简体   繁体   English

Haskell模式匹配问题

[英]Haskell Question on pattern matching

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: 我正在尝试编写一个接受列表的函数,如果按排序顺序返回true,否则返回false:

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. 根据我们的分配,所有头和尾操作都应记为“ x:xs”类型的语法。

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? 从本质上讲,这个问题可以归结为:如何用“ x:xs”类型的语法表示(head(tail list1))?

Cheers, -Zigu 干杯,-子鼓

Your pattern is almost correct, you just need to surround it with parentheses: 您的模式几乎是正确的,只需要用括号括起来即可:

myordered (y:x:xs)

Also note that there's no need to surround y and x with parentheses in y <= x . 另外请注意, yx不需要用y <= x括号括起来。

Also there's a semantic mistake in your second version: 在第二个版本中也存在语义错误:

myordered(xs) here xs refers to the tail of tail, but you want the whole tail, so you should do myordered (x:xs) or alternatively: myordered(xs)在这里xs指的是尾巴的尾巴,但是您想要整个尾巴,因此您应该执行myordered (x:xs)或选择:

myordered (y:xs@(x:_))
 | y <= x = myordered xs
 | otherwise  = False

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. 表示: xs是该列表的尾部, x是该尾部的头部, _ (被忽略)是尾部的尾部。

How about another way to do this with the help of zipWith function available in Data.List 如何在Data.List提供的zipWith函数的帮助下执行此操作的另一种方式

 myordered xs= and $ zipWith (<=) xs (tail xs)

zipWith function takes two list and apply a function. zipWith函数接受两个列表并应用一个函数。 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 and获取布尔值列表,并且仅当列表中的所有值均为True时才返回True

How about 怎么样

isordered :: [Int] →  Bool
isordered [] = True
isordered xs = foldl (&&) True $ zipWith (<=) xs $ tail xs

Oh, and just for fun: 哦, 只是为了好玩:

isordered :: [Int] →  Bool
isordered [] = True
isordered (x:xs) = (foldl comp (Just x) xs) /= Nothing
   where comp (Just a) b = if a ≤ b then Just b else Nothing
         comp Nothing _ = Nothing  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM