Skip to content

Instantly share code, notes, and snippets.

@funrep
Created May 21, 2022 09:52
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 funrep/45cba952c5b3616b5ade05e37e7c02b6 to your computer and use it in GitHub Desktop.
Save funrep/45cba952c5b3616b5ade05e37e7c02b6 to your computer and use it in GitHub Desktop.
-- Does anyone understand what this code does?
-- What is a and b?
-- We add two amounts
-- We know that an "amount" is an Int
type TransferId1 = Int
type Amount1 = Int
add1 :: Amount1 -> Amount1 -> Amount1
add1 a b = a + b
-- Is this an improvement?
-- Our function name is shorter
-- And it's clear that we add together amounts
-- but we can
transferId1 = 1 :: TransferId1
amount1 = 42 :: Amount1
-- add1 amount1 amount1
-- -> 84 OK!
-- add1 transferId1 amount1
-- -> 43 should ERROR!
newtype TransferId2 = TransferId2 Int
deriving (Show)
newtype Amount2 = Amount2 Int
deriving (Show, Num)
add2 :: Amount2 -> Amount2 -> Amount2
add2 (Amount2 a) (Amount2 b) = Amount2 $ a + b
transferId2 = TransferId2 1
amount2 = Amount2 42
-- add2 amount2 amount2
-- -> Amount2 84 OK!
-- add2 transferId2 amount2
-- -> ERROR, nice!
data Currency = SEK | NOK
deriving (Eq, Show)
-- We want to represent
amountSek2 = Amount2 499
amountNok2 = Amount2 299
-- add2 amountSek2 amountNok2
-- -> 798 should ERROR!
data Amount3 = Amount3
{ amount :: Amount2
, currency :: Currency
} deriving (Show)
add3 :: Amount3 -> Amount3 -> Maybe Amount3
add3 (Amount3 a c1) (Amount3 b c2)
| c1 == c2 = Just $ Amount3 (a + b) c1
| otherwise = Nothing
amountSek3 = Amount3 499 SEK
amountNok3 = Amount3 499 NOK
-- add3
-- add3 amountSek3 amountNok3
-- -> Nothing OK!
-- So we get Nothing here, can we do better than this?
-- What do you think?
data SEK4 = SEK4
deriving (Show)
data NOK4 = NOK4
deriving (Show)
data Amount4 a = Amount4
{ amount :: Amount2
, currency :: a
} deriving (Show)
add4 :: Amount4 a -> Amount4 a -> Amount4 a
add4 (Amount4 a c) (Amount4 b _) = Amount4 a c
amountSek4 = Amount4 499 SEK4
amountNok4 = Amount4 499 NOK4
-- add4
-- add4 amountSek4 amountNok4
-- -> ERROR, nice!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment