Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take out a value out of a monad in Haskell?

Tags:

haskell

monads

Is there any way to take "things" out of a monad?

I am developing a game, and I am now trying to understand about databases. I found happstack really nice, but I can't get the thing.

For example, I have this function (hope you are familiar with happstack)

getAllThings :: MonadIO m => m [Thing]
getAllThings = do
            elems <- query GetThings
            return elems

So I get m [Things], but I can't use this in my model! For instance

doSomeThingWithThings :: [Thing] -> Something

I googled this and I found nothing.

like image 392
Illiax Avatar asked Sep 06 '11 04:09

Illiax


People also ask

How do monads work Haskell?

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.

What does bind do in Haskell?

So, the Haskell bind takes a value enclosed in a monad, and returns a function, which takes a function and then calls it with the extracted value.

Is maybe a monad Haskell?

The Maybe type is also a monad. It is a simple kind of error monad, where all errors are represented by Nothing . A richer error monad can be built using the Either type.

Is Haskell list a monad?

Lists are a fundamental part of Haskell, and we've used them extensively before getting to this chapter. The novel insight is that the list type is a monad too! As monads, lists are used to model nondeterministic computations which may return an arbitrary number of results.


2 Answers

You are not supposed to exit IO monad this way (except unsafePerformIO function), but you can still use your function inside it:

process :: MonadIO m => m ()
process = do
          elems <- getAllThings
          let smth = doSomeThingWithThings elems
          -- ...
like image 58
bravit Avatar answered Oct 13 '22 21:10

bravit


After elems <- query GetThings the elems is [Thing] so <- inside do is about getting things out of monad (called bind operation). The last statement return put things inside a monad. So either you can call you other function after getting elems and before return or where ever you are calling getAllThings you can use extract the value using <- from the monad and pass it to your function

like image 32
Ankur Avatar answered Oct 13 '22 23:10

Ankur