Reputation: 31
I'm having an parsing error on the input 'else' but I have no idea how to solve it. I'm still new to this haskell thing.
depot =
do
putStr ("Enter deposit amount: ")
deAmount <- getLine
let redeAmount = read deAmount
if redeAmount > 0 then
let accBal = redeAmount + accBal
else
putStrLn "Please enter amount greater than 0"
Upvotes: 3
Views: 179
Reputation: 1223
I don't have much to add onto sepp2k's answer, but I thought I'd show you how I might write it:
type Balance = Float -- The type of the money balance
type TransactionT m a = StateT Balance m a -- Something that modifies a balance
type Transaction a = TransactionT IO a -- Something that interacts with IO
-- *and* modifies balance
-- Request the user to enter a deposit
getDeposit :: Transaction ()
getDeposit = do
putStr "Enter deposit amount: " -- You don't need () around the argument
amountStr <- liftIO getLine -- This is a consequence of using monad
-- transformers
let amount = read amountStr
if amount > 0
then modify (+ amount) -- Update the balance
else liftIO $ error "Please enter amount greater than 0." -- Raise an
-- exception
Here's a great little tutorial: http://learnyouahaskell.com/.
Here are some sections relevant to the code I wrote:
Oh, and to make your life easier, Hoogle.
Upvotes: 1
Reputation: 370102
The first mistake is that the do
(and everything after it) needs to be indented.
The next mistake is that syntactically let accBal = redeAmount + accBal
can't stand on its own like that. Either it needs to be followed by an in
or it must be directly inside a do
block (being inside an if
which is inside a do
block does not count).
However even if you fix the syntax, it won't do what you want. You can't use let
to reassign variables. As a matter of fact you can't reassign variables at all. If you fix the syntax of your let
, it will simply create a new variable accBal
which will shadow the old variable accBal
. The scope of that new variable will be the then
-block of the if
. Once you leave the if
-block, you'll accBal
will again refer to the old value of accBal
no matter what you did inside the if
.
So to fix your issue, you need to restructure your logic, so it doesn't depend on accBal
being reassigned.
Upvotes: 11