Haskell version of currency conversion

Wrote one Java version on currency convertor https://ratndeo.wordpress.com/2012/10/23/java-submission-to-interfaces/

Here comes sophisticated Haskell version :

data Operation = Add | Sub |Mul |Div
deriving (Show,Eq)

data Unit = Unit | Dollar | INR | EURO
deriving (Show,Eq)

data UnitPair = UnitPair Unit Unit
deriving (Show,Eq)

data Money = Money Double Unit
| MoneyExpression Operation (Money) (Money)
deriving (Show,Eq)

instance Num Money where
a +b = MoneyExpression Add a b
a -b = MoneyExpression Sub a b
a *b = MoneyExpression Mul a b
signum a = error “not defined”
abs a = error “abs not defined”
negate a = error “negate not defined”
fromInteger i = Money (fromInteger i ) Unit

to :: Money -> Unit -> Money

to (Money amount unit ) anotherUnit
= case getExchangeRate(UnitPair unit anotherUnit) of
Just exchangeRate -> Money (amount*exchangeRate) anotherUnit
Nothing -> error $ “exchange rate not set in between ” ++ show unit ++ ” “++ show anotherUnit

where getExchangeRate pair@(UnitPair unit1 unit2) |unit1==unit2 = Just 1
|unit1==Unit = Just 1
|otherwise = case lookup pair exchangeData of
Just exchangeRate -> Just exchangeRate
Nothing ->
case lookup (UnitPair unit2 unit1) exchangeData of
Just x -> Just (1/x)
Nothing -> Nothing

where exchangeData = [(UnitPair Dollar INR,53.0)]
to (MoneyExpression op a b) anotherUnit = applyOp op (to a anotherUnit) (to b anotherUnit)

applyOp Add (Money x unit1) (Money y unit) = Money (x+y) unit1
applyOp Sub (Money x unit1) (Money y unit) = Money (x-y) unit1
applyOp Mul (Money x unit1) (Money y unit) = Money (x*y) unit1

–sample run
((Money 200 Dollar + Money 200 INR) * 2) `to` INR
Money 21600.0 INR

This entry was posted in Haskell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s