Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a function a → b as "monadic" function a → m b

I am currently playing around with Haskell basics and stumbled upon the following "use case":

ghci> let divideTenBy x | x == 0 = Nothing | otherwise = Just (10 / x)
ghci> let composed = divideTenBy <=< return . (*10) <=< divideTenBy <=< return . (-)5
ghci> Just 5 >>= composed
Nothing
ghci> Just 10 >>= composed
Just (-0.5)

So I'm basically mixing monadic and pure functions here and compose them into a monadic function. This works, but the return . (*10) seems to me like a commonly needed thing, so I'm tempted to define a shorthand for it, something like monadify = (return.).

Before I do that, though, I'd like to ask if there are already helpers to deal with that kind of situation. Of course I could also be confused about the whole thing and there are reasons why this should not be done. If so, please tell me.

like image 319
Niklas B. Avatar asked Apr 01 '12 03:04

Niklas B.


1 Answers

There's no reason not to do it. However, it's rarely necessary. For example, your use case can be rewritten as

composed = divideTenBy . (*10) <=< divideTenBy . (-)5
like image 156
Daniel Wagner Avatar answered Sep 29 '22 12:09

Daniel Wagner