Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using when/unless without saving the result of a Monadic action

Tags:

haskell

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.

like image 624
Joe Hillenbrand Avatar asked Jul 07 '15 17:07

Joe Hillenbrand


People also ask

What is a monadic function?

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.

What is the use of monads?

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.

Do monad Haskell?

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.


2 Answers

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
like image 120
mhwombat Avatar answered Apr 28 '23 07:04

mhwombat


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
like image 42
amalloy Avatar answered Apr 28 '23 08:04

amalloy