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?
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 print
s? Would it be at the very beginning or in between them?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With