Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case on monadic value

Tags:

Is there a way to perform a case on the value stored within a monad without having to bind a name to it?

i.e. instead of doing this:

c <- getChar case c of   ... 

Is there a way to do this:

mcase getChar of   ... 

Alternatively, it would be nice if the case statement could be partially applied so:

case of   ... 

would be desugared to:

\a -> case a of   ... 

So you could do this:

getChar >>= case of               ... 
like image 508
pat Avatar asked Mar 22 '11 17:03

pat


People also ask

What is monadic functions?

A monadic function is a function that produces a monadic value. ( Note that we said nothing about its input type) and. Functions of the form f :: a -> m b , where a is the type of the inner value of the monad. ( Call these classic monadic functions)

When to use monads?

monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems.

Is monad a design pattern?

In functional programming, a monad is a software design pattern with a structure that combines program fragments (functions) and wraps their return values in a type with additional computation.

Is a list a monad?

List as a data structure is not a Monad, but the fact that Scala's List implements flatMap is what gives it its monadic super-powers. It also needs to fulfil associativity, left unit and right unit laws to qualify as a Monad.


2 Answers

The proposal mentioned by FUZxxl was now implemented in GHC since 7.6.1, it's called LambdaCase.

Now you can do:

{-# LANGUAGE LambdaCase #-} getChar >>= \case    ... 

Note the \ before the case keyword and the fact that there is no of in that case.

like image 78
Emmanuel Touzery Avatar answered Dec 31 '22 10:12

Emmanuel Touzery


No, not really, but you can move the case into another function and apply it to the result of a monadic action.

f x = case  x of ...  main = do   f <$> getChar 

Alternativly, the following is possible:

getChar >>= \x -> case x of ... 
like image 27
jmg Avatar answered Dec 31 '22 10:12

jmg