Haskell as-patterns

Posted on July 23, 2015

Not a complicated or advanced language feature but one that I don’t use a lot and so keep forgetting about: as-patterns.

When pattern matching you would typically do something like this (an admittedly contrived example)

data Person = Person String Int

getName (Person s _) = s

Once you’ve matched against the constructor you no longer have a reference to the Person as a whole. as-patterns are simply a way to keep a reference to the thing you’re pattern matching against. It makes the following possible

displayPerson person@(Person s i) = getName person ++ "is " show i