Skip to content

Instantly share code, notes, and snippets.

@lachezar
Last active September 5, 2020 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lachezar/e01175890aeb70af8136693cc55ae03e to your computer and use it in GitHub Desktop.
Save lachezar/e01175890aeb70af8136693cc55ae03e to your computer and use it in GitHub Desktop.
Currency in Haskell
{-# 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 :(
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
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