[Haskell-cafe] Pattern guards seen in the wild?
magnus at therning.org
Fri Oct 1 07:02:54 UTC 2021
Anthony Clayden <anthony.d.clayden at gmail.com> writes:
> Browsing some docos for a completely other purpose, I came
> across this code:
>> f' [x, y] | True <- x, True <- y = True
>> f' _ = False
> (In User Guide 188.8.131.52 Matching of Pattern Synonyms.)
> That business with the comma and left-arrows? They're 'Pattern
> guards', Language Report 2010 section 3.13. That also specs
> bindings' introduced by `let`.
> In 10 years of reading Haskell code, I've never seen them. Does
> anybody use them? Are they more ergonomic than guards as plain
> expressions? Are 'local bindings' any different vs shunting the
> to the rhs of the `=`?
> I'd write that code as:
>> f'' [x at True, y at True] = True
>> f'' _ = False
> I can see the rhs of the matching arrow could in general be a
> complex expression. But to express that you could put a more
> Boolean guard(?)
I've used it occasionally, e.g when dealing with exceptions. I
think this is the most recent example:
lastExceptionHandler :: LoggerSet -> SomeException -> IO ()
lastExceptionHandler logger e
| Just TimeoutThread <- fromException e = return ()
| otherwise = do
logFatalIoS logger $ pack $ "(ws) uncaught exception: " <>
(That's the exception handler I installed with
`setUncaughtExceptionHandler` in a web service to deal with
Magnus Therning OpenPGP: 0x927912051716CE39
email: magnus at therning.org
@magthe at mastodon.technology http://magnus.therning.org/
Action is the foundational key to all success.
— Pablo Picasso
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 861 bytes
Desc: not available
More information about the Haskell-Cafe