I had some code like this:
newtype T = T Text
pattern Alice = T "Alice"
This is fine, but I was using "Alice" in other places. So I decided to factor it out like so:
alice :: Text
alice = "Alice"
pattern Alice = T alice
But when I built this with warnings on, I got a warning about an unused variable.
I then realised that:
pattern Alice = T alice
actually matches everything, as opposed just T "Alice"
It then seemed weird that even T "Alice"
was allowed, as "Alice"
is Text
, something which is computed.
But then I saw on the Overloaded Strings docs that:
String literals behave very much like integer literals, i.e., they can be used in both expressions and patterns. If used in a pattern the literal will be replaced by an equality test, in the same way as an integer literal is.
So this raises a few questions:
- Could I even write the pattern
Alice
without enabling the overloaded strings extension? - Can I create pattern synonyms where the RHS requires some computation, and have GHC use
Eq
to match, just like it does for numeric and string literals? Or are numeric and string literals a special case and GHC doesn't allow one to generalise that functionality?
You can use view patterns to perform any computation in the pattern and then use the result to match anything else.
Here you apply
(==alice)
to the argument and match the result againstTrue
.