I have a chaining of functors and I need at some point to wrap my value in a Maybe
:
module Funct where
(>>?) :: Maybe a -> (a -> Maybe b) -> Maybe b
(Just a) >>? f = f a
Nothing >>? _ = Nothing
f1 :: Int -> Maybe Bool
f1 a = if a > 2 then Just (a `mod` 2 == 0) else Nothing
f2 :: Bool -> Char
f2 b = if b then 'a' else 'b'
f3 :: Char -> Maybe Int
f3 c = if c == 'a' then Just 1 else Nothing
fm :: Int -> Maybe Int
fm x = f1 x >>? f2 >>? f3
^
Is there a reverse method for fmap particular for Maybe
or do I have to implement it?
Implemented
myWrapper :: Char->Maybe Char
myWrapper c = Just c
fm x = f1 x >>? myWrapper . f2 >>? f3 -- is there any built in way more concise?
I am asking because when chaining I suppose you would need wrappers for other monads too like Either
.
(is there any built in way more concise?)
Sure:
myWrapper = Just
Or inline:
fm x= f1 x>>? Just . f2 >>? f3
Data constructors can be viewed as plain functions, so you can compose them with other functions.