typestar

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

  1. newtype Tag = Tag String wraps a string so it can carry its own instances.
  2. The Show instance defines show (Tag name) = '#' : name, so a tag renders with a hash in front.
  3. The Eq instance compares map toLower a == map toLower b, which makes sameTopic true for two spellings of one tag.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Typeclasses, step 20 of 27 in Language basics.

← Previous Next →