Custom instances in Haskell
Hand-written Show and Eq instances decide how a value prints and what counts as equal.
module Tags where
import Data.Char (toLower)
-- A tag keeps the spelling the author typed.
newtype Tag = Tag String
-- Writing Show by hand controls exactly how a value is rendered.
instance Show Tag where
show (Tag name) = '#' : name
-- Domain equality: normalize both sides, then compare.
instance Eq Tag where
Tag a == Tag b = map toLower a == map toLower b
-- So two spellings of one tag are the same tag.
sameTopic :: Bool
sameTopic = Tag "Haskell" == Tag "haskell"
How it works
newtype Tag = Tag Stringwraps a string so it can carry its own instances.- The Show instance defines
show (Tag name) = '#' : name, so a tag renders with a hash in front. - The Eq instance compares
map toLower a == map toLower b, which makessameTopictrue for two spellings of one tag.
Keywords and builtins used here
BoolEqShowStringTagimportinstancemodulenewtypesameTopictoLowerwhere
The run, in numbers
- Lines
- 18
- Characters to type
- 475
- Tokens
- 61
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 52 seconds.
Step 2 of 3 in Typeclasses, step 20 of 27 in Language basics.