[英]How to replace case-of or matching pattern with guards in Haskell?
I am trying (as a part of learning) replace case-of expression with expression with guards.我正在尝试(作为学习的一部分)用带有警卫的表达式替换表达式的大小写。 This is a function with case-of
这是一个带有外壳的 function
myList :: [a] -> String
myList xs = case xs of [] -> "empty"
[x] -> "one"
xs -> "more"
I've managed to write a function with where and matching pattern我已经设法编写了一个 function 与 where 和匹配模式
myList' :: [a] -> String
myList' xs = someF xs
where someF [] = "empty"
someF [x] = "one"
someF xs = "more"
However, I could not make another function myList'' which is using guards (|).但是,我无法制作另一个使用警卫 (|) 的 function myList''。 I am new in Haskell, and would much appreciate if somebody can help me with this problem.
我是 Haskell 的新手,如果有人能帮助我解决这个问题,我将不胜感激。 Thank you in advance.
先感谢您。 Al
铝
You can make use of pattern guards , for example:您可以使用模式防护,例如:
myList'' :: [a] -> String
myList'' xs
| [] <- xs = "empty"
| [_] <- xs = "one"
| otherwise = "more"
Or you can make use of null:: Foldable f => fa -> Bool
and drop:: Int -> [a] -> [a]
to check if the list is empty:或者您可以使用
null:: Foldable f => fa -> Bool
和drop:: Int -> [a] -> [a]
检查列表是否为空:
myList'' :: [a] -> String
myList'' xs
| null xs = "empty"
| null (drop 1 xs) = "one"
| otherwise = "more"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.