Question

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.

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top