Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - How to use <- in where clauses

Tags:

haskell

I have the following code:

foo :: Int -> IO ()
foo n = do
    x <- bar 6
    print "foo running..."
    print x


bar :: Int -> IO Int
bar n = do
    print "bar running..."
    return (n*2)

Now I want to put the "x <- bar 6" part in a where clause, like this:

foo :: Int -> IO ()
foo n = do
    print "foo running..."
    print x
    where
        x <- bar 6

bar :: Int -> IO Int
bar n = do
    print "bar running..."
    return (n*2)

How do I do this?

like image 978
Yahya Uddin Avatar asked Nov 16 '14 21:11

Yahya Uddin


2 Answers

This isn't allowed. A where clause doesn't impose an evaluation order, which is necessary for most Monads, such as IO. If this were possible, when would bar 6 be executed relative to the two prints? Would it be at the very beginning or in between them?

like image 151
David Young Avatar answered Sep 19 '22 08:09

David Young


How do I do this?

It doesn't make sense. I'm sorry.

The following, in a do block:

a <- b
c

is equivalent to:

b >>= (\a -> c)

So a <- b alone, would be equivalent to: b >>= (\a ->) which is a grammar error.

There's no need for you to store x in a where clause anyway. In your program:

foo :: Int -> IO ()
foo n = do
    x <- bar 6
    ...

after x <- bar 6, you can reuse x everywhere within the do block.

like image 28
Shoe Avatar answered Sep 19 '22 08:09

Shoe