Is there a way to write this without the variable x
?
foo = do
x <- checker bar
when x dostuff
I'm imagining something similar to LambdaCase:
foo' = do
checker bar >>= \case
True -> dostuff
_ -> return ()
but without the second case pattern, obviously.
A monadic function is a function with a single argument, written to its right. It is one of three possible function valences; the other two are dyadic and niladic. The term prefix function is used outside of APL to describe APL's monadic function syntax.
A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.
Any instance of the Monad class can be used in a do-block in Haskell. In short, the do notation allows you to write monadic computations using a pseudo-imperative style with named variables. The result of a monadic computation can be "assigned" to a variable using a left arrow <- operator.
In Control.Monad.Extra
, check out whenM
. For your example, that would be:
foo = whenM (checker bar) doStuff
Here's a longer example, just to show you how to multiple statements in your whenM
structure.
foo = do
doStuff1
doStuff2
whenM (checker bar) $ do
doStuff3
doStuff4
doStuff5
doStuff6
The most straightforward answer is to desugar the do
by hand, and then see if you can write some code that's equivalent but prettier. Your do
desugars to:
checker bar >>= \x -> when x dostuff
So, the answer will have to look like checker bar >>= f
, where f
is equivalent to
\x -> when x dostuff
Well, that's a lot like partially applying when
, right? Except you want to supply the second argument instead of the first, so you need to flip
it:
checker bar >>= flip when dostuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With