LINUX.ORG.RU

История изменений

Исправление monk, (текущая версия) :

class AccountClass a where
  changeBalance :: a -> Rational -> a

withdraw i a | i > 0 = changeBalance a (-i)

deposit i a | i > 0 = changeBalance a i

data Account = Account Rational | AccountError String
  deriving Show

instance AccountClass Account where
  changeBalance (Account balance) change = 
    if balance + change > 0
    then Account (balance + change)
    else AccountError "Insufficient funds"

balance (Person (Account a)) = a

data Person = Person Account

withPerson f (Person a) = Person $ f a

main = do
  john <- newIORef $ Person $ Account 0
  jack <- newIORef $ Person $ Account 0
  modifyIORef john $ withPerson $ deposit 100
  modifyIORef jack $ withPerson $ deposit 300
  modifyIORef john $ withPerson $ withdraw 10
  modifyIORef jack $ withPerson $ withdraw 50
  readIORef jack >>= putStrLn . show . balance  -- // 250
  readIORef john >>= putStrLn . show . balance  -- // 90

Исходная версия monk, :

class AccountClass a where
  changeBalance :: a -> Rational -> a

withdraw i a | i > 0 = changeBalance a (-i)

deposit i a | i > 0 = changeBalance a i

data Account = Account Rational | AccountError String
  deriving Show

instance AccountClass Account where
  changeBalance (Account balance) change = 
    if balance + change > 0
    then Account (balance + change)
    else AccountError "Insufficient funds"

balance (Person (Account a)) = a

data Person = Person Account

withPerson f (Person a) = Person $ f a

main = do
  John <- newIORef $ Person $ Account 0
  Jack <- newIORef $ Person $ Account 0
  modifyIORef John $ withPerson $ deposit 100
  modifyIORef Jack $ withPerson $ deposit 300
  modifyIORef John $ withPerson $ withdraw 10
  modifyIORef Jack $ withPerson $ withdraw 50
  readIORef Jack >>= PutStrLn . show . balance  -- // 250
  readIORef John >>= PutStrLn . show . balance  -- // 90