Haskell code is often pleasingly elegant, but I particularly liked this code which uses the View Patterns1 extension to good effect:
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Map.Strict as M
import qualified Data.Text as T
....
r :: T.Text -> T.Text
r (T.stripPrefix "inc:" -> Just k) = handleInc k
r (T.stripPrefix "h1:" -> Just k) = header k
r ((`M.lookup` snippets) -> Just h) = h
r k = unknown k
I suppose the key insight is that in the context of View Patterns
functions of type u -> Maybe v
are great to optionally match against
some u
and extract a v
.
Some Haskell libraries e.g. Data.Text2 have functions3 specifically to enable this sort of thing.
It struck me as a more principled version of this sort of Perl code:
if ($foo =~ /^h1:(.*)/) { header($1) }
You can do much more with View Patterns: the GHC wiki lists some examples4.
References
- 1. https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/view_patterns.html
- 2. https://hackage.haskell.org/package/text-2.0.2/docs/src/Data.Text.html
- 3. https://hackage.haskell.org/package/text-2.0.2/docs/Data-Text.html#g:22
- 4. https://gitlab.haskell.org/ghc/ghc/-/wikis/view-patterns