user1151874
user1151874

Reputation: 279

haskell subtract error

answerFalse::Int->IO()
answerFalse hp=do
            hp--
            if hp<=0 then
                putStrLn"================Game Over================"

            else
                print(hp)

i already declare hp as int with value 3 now my problem is when i put "hp--", it shows error

 Couldn't match expected type `IO a0' with actual type `Int'

but if i put "--hp", the result print is 3 not 2.

i also tried let hp=hp-1, the system stuck there.

Upvotes: 0

Views: 214

Answers (2)

Rijk
Rijk

Reputation: 612

things like i++ can be modelled in Haskell by using State monad. You can look examples on haskellwiki

Upvotes: 0

dflemstr
dflemstr

Reputation: 26157

You can't modify variables in Haskell. hp++ and ++hp (or hp-- and --hp) don't work in Haskell at all; the reason why --hp compiles is that -- creates a comment which comments out the hp part.

What you are trying to do is this:

answerFalse hp =
  if hp - 1 <= 0
  then putStrLn "================Game Over================"
  else print hp

You can also do it like this, by creating a new variable:

answerFalse hp = do
  let newHp = hp - 1
  if newHp <= 0
    then putStrLn "================Game Over================"
    else print hp

You need to review your basic Haskell knowledge by reading beginner tutorials. This question provides excellent resources for you.

Upvotes: 6

Related Questions