Last active
September 5, 2020 15:12
-
-
Save lachezar/e01175890aeb70af8136693cc55ae03e to your computer and use it in GitHub Desktop.
Currency in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE GeneralizedNewtypeDeriving #-} | |
module Main where | |
newtype USD = USD Int deriving (Show, Num) | |
newtype EUR = EUR Int deriving (Show, Num) | |
main :: IO () | |
main = do | |
print $ (USD 12) + (USD 11) | |
print $ (EUR 1) + (EUR 2) | |
-- Does not compile: print $ (EUR 1) + (USD 2) | |
print $ (USD 11) + 12 -- this compiles :( |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
newtype USD = USD Int deriving (Show) | |
newtype EUR = EUR Int deriving (Show) | |
class Currency a where | |
p :: a -> a -> a | |
instance Currency USD where | |
p (USD a) (USD b) = USD $ a + b | |
instance Currency EUR where | |
p (EUR a) (EUR b) = EUR $ a + b | |
main :: IO () | |
main = do | |
print $ (USD 12) `p` (USD 11) | |
print $ (EUR 1) `p` (EUR 2) | |
-- Does not compile: print $ (EUR 1) `p` (USD 2) | |
-- Does not compile: print $ (USD 11) `p` 12 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude hiding ((+), (-)) | |
import qualified Prelude as P | |
class Money m where | |
unwrap :: m -> Int | |
wrap :: Int -> m | |
(+) :: m -> m -> m | |
(+) a b = wrap $ (unwrap a) P.+ (unwrap b) | |
(-) :: m -> m -> m | |
(-) a b = wrap $ (unwrap a) P.- (unwrap b) | |
newtype USD = USD Int deriving Show | |
newtype EUR = EUR Int deriving Show | |
instance Money USD where | |
unwrap (USD a) = a | |
wrap = USD | |
instance Money EUR where | |
unwrap (EUR a) = a | |
wrap = EUR | |
data Budget a = Budget { | |
revenue :: a, | |
expenditures :: a | |
} deriving Show | |
profit :: Money a => Budget a -> a | |
profit (Budget revenue expenditures) = revenue - expenditures | |
main :: IO () | |
main = do | |
print $ (USD 12) + (USD 22) | |
print $ (EUR 1) + (EUR 2) | |
let budget = Budget (USD 10) (USD 3) | |
print budget | |
print $ profit budget | |
-- Does not compile: print $ (EUR 1) + (USD 2) | |
-- Does not compile: print $ (USD 11) + 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment