如何在Haskell中用卫士替换case of或matching pattern



我正在尝试(作为学习的一部分(用带卫士的表达式替换表达式的大小写。这是情况下的函数

myList :: [a] -> String
myList xs = case xs of []  -> "empty"
[x] -> "one"
xs  -> "more"

我已经成功地编写了一个带有where和匹配模式的函数

myList' :: [a] -> String
myList' xs = someF xs 
where someF []  = "empty"
someF [x] = "one"
someF xs  = "more"

但是,我无法创建另一个使用保护(|(的函数myList"。我是哈斯克尔的新手,如果有人能帮我解决这个问题,我将不胜感激。提前谢谢。Al

您可以使用模式保护,例如:

myList'' :: [a] -> String
myList'' xs
| [] <- xs = "empty"
| [_] <- xs = "one"
| otherwise = "more"

或者您可以使用null :: Foldable f => f a -> Booldrop :: Int -> [a] -> [a]来检查列表是否为空:

myList'' :: [a] -> String
myList'' xs
| null xs = "empty"
| null (drop 1 xs) = "one"
| otherwise = "more"

最新更新