I am currently having problems understanding the Either-Monad in Haskell. Either is an instance of the Monad data type. Therefore I can use the Either within a Do block like this ...
type MyAccount = Integer
transaction :: Integer -> MyAccount -> Either String MyAccount
transaction value account | value + account < 0 = Left "Error: insufficient funds!"
| otherwise = return $ account + value
Test1 :: Either String MyAccount
Test1 = do
account_state <- return 1000
r1 <- transaction (-200) account_state
r2 <- transaction (-1000) r1
return r2
This is a working piece of Code: account_state, r1 and r2 are of type Integer. Therefore the function transaction works properly. However..
Test2 :: Either String MyAccount
Test2 = do
account_state <- return 1000
r1 <- transaction (-2000) account_state
r2 <- transaction (-1000) r1
return r2
In Test2 I have change the transaction value from -200 to -2000. Therefore r1 should be the String "Error: insufficient funds!". Since transaction does not work with Strings, there should be a type error. But there is not ... What is Haskell doing here ?
transaction (-1000) ("Error: insufficient funds!") should not work.