如何在高阶函数haskell中使用Maybe?

How to use Maybe in higher order function haskell?

我想解决下面的问题,其中 f returns Nothing,然后删除第一个元素。如果freturns只是x,第一个元素就换成x。我在下面的回答对 Nothing 有效,但我不明白如何在函数内部区分 Nothing 和 Just

change:: (a -> Maybe a) -> [a] -> [a]
change f [] = []
change f (x:xs) = xs

更改(\x -> 无)[1..5] == [2..5]

改变(\x -> 仅 10) [1,2,3] == [10,2,3]

对于一个简单的解决方案,您可以像这样在 f x 上进行模式匹配(使用 case):

change:: (a -> Maybe a) -> [a] -> [a]
change _ [] = []
change f (x:xs) =
   case f x of
       Just x' -> x':xs
       Nothing -> xs

这应该符合您的描述


对于较短的,您可以使用 maybeToList 并像这样连接部分:

change:: (a -> Maybe a) -> [a] -> [a]
change _ [] = []
change f (x:xs) = (maybeToList $ f x) ++ xs