Haskell - How to use <- in where clauses

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 part "x <- bar 6" in the where clause, for example:

 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 can I do it?

+7
source share
2 answers

It is forbidden. A where does not impose the evaluation order that most Monads need, such as IO . If it were possible, when bar 6 would be executed relative to two print s? Will it be at the very beginning or between them?

+15
source

How to do it?

It does not make sense. Sorry.

In the do block, the following:

 a <- b c 

equivalent to:

 b >>= (\a -> c) 

Only a <- b will be equivalent: b >>= (\a ->) , which is a grammar error.

There is no need to store x in the where clause anyway. In your program:

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

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

+5
source

All Articles