Skip to content

Commit

Permalink
invert: rename from representing-enums, and remove Rep
Browse files Browse the repository at this point in the history
  • Loading branch information
chris-martin committed Sep 24, 2019
1 parent 0f9376c commit d5ea969
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 74 deletions.
62 changes: 62 additions & 0 deletions invert.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}

import GHC.Generics (Generic)
import Generics.Deriving.Enum (GEnum (genum))
import qualified Data.Map.Strict as Map

data Product = Basic | Standard | Pro
deriving stock (Generic, Show)
deriving anyclass GEnum

data Frequency = Monthly | Annual
deriving stock (Generic, Show)
deriving anyclass GEnum

data Bill = Bill Product Frequency
deriving stock (Generic, Show)
deriving anyclass GEnum

encodeProduct :: Product -> String
encodeProduct = \case
Basic -> "p1"
Standard -> "p2"
Pro -> "p3"

encodeBill :: Bill -> Integer
encodeBill = \case
Bill Basic Monthly -> 10
Bill Basic Annual -> 11
Bill Standard Monthly -> 20
Bill Standard Annual -> 21
Bill Pro Monthly -> 30
Bill Pro Annual -> 31

invert :: (GEnum a, Ord b) => (a -> b) -> b -> Maybe a
invert f =
let
reverseMap = foldMap (\a -> Map.singleton (f a) a) genum
in
\b -> Map.lookup b reverseMap

decodeProduct :: String -> Maybe Product
decodeProduct = invert encodeProduct

decodeBill :: Integer -> Maybe Bill
decodeBill = invert encodeBill

main =
do
putStrLn (encodeProduct Basic)
putStrLn (encodeProduct Standard)

putStrLn (show (decodeProduct "p1"))
putStrLn (show (decodeProduct "xyz"))

putStrLn (show (encodeBill (Bill Basic Annual)))
putStrLn (show (encodeBill (Bill Pro Monthly)))

putStrLn (show (decodeBill 31))
putStrLn (show (decodeBill 50))
8 changes: 8 additions & 0 deletions outputs/invert.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
p1
p2
Just Basic
Nothing
11
30
Just (Bill Pro Annual)
Nothing
8 changes: 0 additions & 8 deletions outputs/representing-enums.txt

This file was deleted.

65 changes: 0 additions & 65 deletions representing-enums.hs

This file was deleted.

2 changes: 1 addition & 1 deletion tools/outputs.nix
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ in
(run "hashing.txt" ../hashing.hs {})
(run "hello-world.txt" ../hello-world.hs {})
(run "mutable-references.txt" ../mutable-references.hs {})
(run "representing-enums.txt" ../representing-enums.hs {})
(run "invert.txt" ../invert.hs {})
(run "threads.txt" ../threads.hs { sed = ["s!^fork.*$!...!"]; })
(run "timeouts.txt" ../timeouts.hs {})
(run "transactions.txt" ../transactions.hs { sed = ["s!\\[.*\\]!...!"]; })
Expand Down

0 comments on commit d5ea969

Please sign in to comment.