[Haskell-cafe] Pattern guards in comprehensions

Manuel Gómez targen at gmail.com
Tue Aug 11 00:54:40 UTC 2015


On Sun, Aug 9, 2015 at 10:23 PM, Richard Eisenberg <eir at cis.upenn.edu> wrote:
> This can be done today:
>
>> allMinus m ns = [ n' | n <- ns, Just n' <- [n -? m] ]
>
> The syntax is a bit regrettable, but it works quite well.

On a somewhat related note, this trick is a nice way to introduce
let-like bindings in languages like Python that have comprehension
syntax and no explicit support for pure intermediate bindings:

    [ str(x) + ' is ' + str(i) + ' dozens' for i in range(1, 9) for x
in [12*i] ]

It’s also useful when you want to simulate monadic-ish things sometimes:

    x = {'a': { 'b': 'c', 'd': 'e'}, 'f': 'g'}

    [
      z
      for y in [x.get('a')] if y
      for z in [y.get('b')] if z
    ]
    # => ['c']

    [
      z
      for y in [x.get('q')] if y
      for z in [y.get('b')] if z
    ]
    # => []

Almost feels like having some simple monads!


More information about the Haskell-Cafe mailing list