[GHC] #12001: RFC: Add pattern synonyms to base
GHC
ghc-devs at haskell.org
Fri May 13 19:22:35 UTC 2016
#12001: RFC: Add pattern synonyms to base
-------------------------------------+-------------------------------------
Reporter: Iceland_jack | Owner:
Type: feature request | Status: new
Priority: normal | Milestone:
Component: libraries/base | Version: 7.10.3
Resolution: | Keywords:
Operating System: Unknown/Multiple | Architecture:
| Unknown/Multiple
Type of failure: None/Unknown | Test Case:
Blocked By: | Blocking:
Related Tickets: | Differential Rev(s):
Wiki Page: |
-------------------------------------+-------------------------------------
Comment (by Iceland_jack):
=== GHC.Generics ===
{{{#!hs
pattern From :: Generic a => (Rep a) x -> a
pattern From rep <- (from → rep)
where From rep = to rep
pattern From1 :: Generic1 f => (Rep1 f) a -> f a
pattern From1 rep <- (from1 → rep)
where From1 rep = to1 rep
}}}
or corresponding `To`, `To1` patterns.
=== Text.Read ===
{{{#!hs
pattern Read :: Read a => a -> String
pattern Read a <- (readMaybe -> Just a)
}}}
with the caveat that they parse different types,
{{{#!hs
foo :: String -> String
foo (Read 42) = "answer"
foo (Read n) = "some other number " ++ show n
foo _ = "can't parse"
}}}
{{{
ghci> foo "()"
"some other number ()"
}}}
If the types are made explicit with #11350
{{{#!hs
foo :: String -> String
foo (Read @Integer 42) = "answer"
foo (Read @() n) = "some other number " ++ show n
foo _ = "can't parse"
}}}
it is a common action and pattern (search for `pattern` and `readMaybe ->
Just`), and is often use to pattern match on numbers. Artificially
restricting the type avoids it matching `()`
{{{#!hs
pattern ReadNumber :: (Num a, Read a) => a -> String
}}}
This is cool
{{{
ghci> [ n | ReadNumber n <- words "from 2010 ... 2016 they were 4" ]
[2010,2016,4]
}}}
--
Ticket URL: <http://ghc.haskell.org/trac/ghc/ticket/12001#comment:7>
GHC <http://www.haskell.org/ghc/>
The Glasgow Haskell Compiler
More information about the ghc-tickets
mailing list