[Haskell-cafe] Last statement in 'do' must be an expression error.

Ulf Norell ulfn at cs.chalmers.se
Thu Aug 17 04:31:06 EDT 2006


On Aug 17, 2006, at 10:18 AM, Szymon Ząbkiewicz wrote:

> Hi.
>
> When trying to compilke this code:
>
> {...}
> 8.if (a == 0) && (b == 0)
> 9.       then do
> 10.             nr1 <- read (prompt "enter 1. number: ")
> 11.             nr2 <- read (prompt "enter 2. number: ")
> 12.       else do
> 13.            let nr1 = a
> 14.                nr2 = b
> {...}
>
> The compiler tells me thats there's an error on line 10:
> "The last statement in a 'do' construct mesy be an expression"
>
> Could you tell me how to change it so that the "declaration" of the
> first nr1 and nr2 is still in the "then" block.

The problem is that variables defined in the branch of an if are  
local to the branch. If you want to use them outside you have to  
return them from the branch:

do
   (nr1, nr2) <-
     if (a == 0) && (b == 0)
     then do
            nr1 <- read (prompt "enter 1. number: ")
            nr2 <- read (prompt "enter 2. number: ")
            return (nr1, nr2)
     else do
            let nr1 = a
                nr2 = b
            return (nr1, nr2)

/ Ulf


More information about the Haskell-Cafe mailing list