[Haskell-cafe] Pattern guards seen in the wild?
Magnus Therning
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 6.7.4.5 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
> 'local
> 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
> Boolean
> expressions? Are 'local bindings' any different vs shunting the
> `let`
> 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
> more
> complex expression. But to express that you could put a more
> complex
> 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: " <>
displayException e
flushLogStr logger
```
(That's the exception handler I installed with
`setUncaughtExceptionHandler` in a web service to deal with
https://github.com/yesodweb/wai/issues/852)
/M
--
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...
Name: signature.asc
Type: application/pgp-signature
Size: 861 bytes
Desc: not available
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20211001/b73576c8/attachment.sig>
More information about the Haskell-Cafe
mailing list