Reputation: 33
i'd like to know if in this portion of code is possible to replace the case statement with guards:
firstFunction :: String -> Maybe MyType
secondFunction :: MyType -> Integer
myFunction :: String -> Maybe Integer
myFunction xs = case firstFunction xs of
Nothing -> Nothing
Just x -> Just( secondFunction x )
Thank you in advance!
Upvotes: 3
Views: 356
Reputation: 476709
You could use a pattern guard [Haskell-wiki], like:
myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
| otherwise = Nothing
But what you here do is basically "fmap
" the result of firstFunction
, like:
myFunction :: String -> Maybe Integer
myFunction xs = fmap secondFunction (firstFunction xs)
fmap :: Functor f => (a -> b) -> f a -> f b
is used to "map" over a functor. Now Maybe
is a functor, defined as:
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a)
which is basically the logic you wrote here.
Upvotes: 4