Why can't I only implement these functions with the Functor / Applicative constraint?

Consider the following features taken from the answers to this set of problems :

func6 :: Monad f => f Integer -> f (Integer,Integer)
func6 xs = do
    x <- xs
    return $ if x > 0 then (x, 0)
                      else (0, x)

func6' :: Functor f => f Integer -> f (Integer,Integer)
-- slightly unorthodox idiom, with an partially applied fmap
func6' = fmap $ \x -> if x > 0 then (x,0) else (0,x)

-- func7 cannot be implemented without Monad if we care about the precise
-- evaluation and layzness behaviour:
-- > isJust (func7 (Just undefined))
-- *** Exception: Prelude.undefined
--
-- If we care not, then it is equivalent to func6, and there we can. Note that
-- > isJust (func6 (Just undefined))
-- True    
func7 :: Monad f => f Integer -> f (Integer,Integer)
func7 xs = do
    x <- xs
    if x > 0 then return (x, 0)
             else return (0, x)

-- func9 cannot be implemented without Monad: The structure of the computation
-- depends on the result of the first argument.
func9 :: Monad f => f Integer -> f Integer -> f Integer -> f Integer
func9 xs ys zs = xs >>= \x -> if even x then ys else zs

Although I understand the counterexample for func7, I do not understand the reasoning about why we can implement func7it func9using only monads. How do the laws of the monad / applicative / functor correspond to the above reasoning?

+4
source share
2 answers

func6 versus func7 . ( , , , func6 @Maybe , , , Just Nothing, .)

func9, , Monad , , , xs, . ( "functorial context" "" , , " ".) :

func9 (fmap read getLine) (putStrLn "Even!") (putStrLn "Odd!")

fmap, (<*>) (>>=):

(<$>) :: Functor f     =>   (a ->   b) -> (f a -> f b) -- (<$>) = fmap
(<*>) :: Applicative f => f (a ->   b) -> (f a -> f b)
(=<<) :: Monad f       =>   (a -> f b) -> (f a -> f b) -- (=<<) = filp (>>=)

a -> b, fmap, f, Functor, fmap . (<*>) , - a -> b, f (a -> b), . (>>=) a -> f b , f a.

Monad Applicative Haskell , ( ) Functor, Applicative Monad.

+1

, - ; , , , - .

, , , :sprint GHCi, .

func6

x6 func6 .

λ> x6 = Just . bool 'a' 'b' =<< Just True

.

λ> :sprint x6
x6 = _

'isJust x6'.

λ> isJust x6
True

, x6 . .

λ> :sprint x6
y = Just _

? bool 'a' 'b', , Maybe Just. , .

func7

x7 func7 .

λ> x7 = bool (Just 'a') (Just 'b') =<< Just True
x :: Maybe Char

, .

λ> :sprint x7
x = _

isJust.

λ> isJust x7
True

Just ( , " " " " ).

λ> :sprint x7
x = Just 'b'

? bool, , Just.

+4

Source: https://habr.com/ru/post/1694918/


All Articles