John Montana
John Montana

Reputation: 175

How to use Maybe in higher order function haskell?

I wanted to solve the below problem where f returns Nothing, then the first element is removed. If f returns Just x, the first element is changed with x. My answer below works correctly for Nothing but I couldn't understand how to differentiate Nothing and Just inside the function

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

change(\x -> Nothing) [1..5] == [2..5]

change(\x -> Just 10) [1,2,3] == [10,2,3]

Upvotes: 2

Views: 140

Answers (1)

Random Dev
Random Dev

Reputation: 52270

for a simple solution you can just pattern-match (with case) on f x like this:

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

that should do what you described


for a shorter one you can use maybeToList and concat the parts like this:

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

Upvotes: 7

Related Questions