Skip to content

Instantly share code, notes, and snippets.

@ryanwinchester
Last active December 19, 2017 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwinchester/8997e52eeb50bf3b5b6395bc72173948 to your computer and use it in GitHub Desktop.
Save ryanwinchester/8997e52eeb50bf3b5b6395bc72173948 to your computer and use it in GitHub Desktop.

Here’s an example of an list comprehension in Haskell from Wikipedia:

a = [(x,y) | x <- [1..5], y <- [3..5]]
-- [(1,3),(1,4),(1,5),(2,3),(2,4) ...

In this example, a list of pair of integers is constructed from 2 lists of integers.

Here is what that example would be in Python:

a = [(x, y) for x in range(1,6) for y in range(3, 6)]
# [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4) ...

Here’s what it would be in mathematics (except we are dealing with sets, not lists, but I’ll only refer to lists from here on.):

Let (a, b) be an ordered list of elements

{(x, y)|x ∈ {1,2,3,4,5}, y ∈ {3,4,5}}

One can filter out unwanted elements with predicates, and apply arbitrary functions to elements of the result. Let’s say we only want even numbers from the first list, and we want the sum of x and y, continuing on our examples:

a = [x+y | x <- [1..5], y <- [3..5], x `mod` 2 == 0]
a = [x + y for x in range(1,6) for y in range(3, 6) if x % 2 == 0]
{x+y|x ∈ {1,2,3,4,5}, y ∈ {3,4,5}, x is even}

Here's the elixir version:

a = for x <- 1..5, y <- 3..5, do: {x, y}
# [{1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, ...

with filtering:

a = for x <- 1..5, y <- 3..5, rem(x, 2) == 0, do: {x, y}
# [{2, 3}, {2, 4}, {2, 5}, {4, 3}, {4, 4}, {4, 5}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment