Skip to content

Allow expressions in patterns

I've outlined a proposal for extending pattern synonyms to depend on terms (PatternFamilies), the name is less than ideal but I'll keep the page under that name for now. The proposal's introduction has been rewritten.

The simplest use case are patterns that matches only when a set contains an element (IsMember) or when a set does not contain an element (NotMember):

[[Image(wiki:PatternFamilies:member.png)]]

    hasKeys :: Set Item -> IO ()
    hasKeys (IsMember  "keys") =             leaveHouse
    hasKeys (NotMember "keys") = findKeys >> leaveHouse

or a pattern that matches a map if the key exists:

[[Image(wiki:PatternFamilies:lookup.png)]]

used like this:

    age :: Map Person Age -> String
    age (Lookup "Alice" 60)  = "Alice is 60 years old!"
    age (Lookup "Alice" age) = "Alice is " ++ show age ++ "."
    age (Lookup "Bob" _)     = "No info on Alice but we know how old Bob is."
    age _                    = "..."

Further details and examples can be found here: PatternFamilies, I discussed it with several people ICFP 2014. This would not require a new extension but would extend PatternSynonyms. This feature can be quite useful, especially when working with deeply nested structures (ASTs, JSON, XML, ...).

If people are fine with it I will implement it.

Trac metadata
Trac field Value
Version
Type FeatureRequest
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information