Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active December 15, 2015 13:18
Show Gist options
  • Save DmitrySoshnikov/5266337 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/5266337 to your computer and use it in GitHub Desktop.

List comprehensions

Basic idea in theoretical programming: a notation for Set builders from math.

Basic idea in practical programming: syntactic sugar for "map + filter" functional methods:

Example of map and filter, ES6

let x = N.filter(x => x > 10).map(x => x * x);

Can be written as:

let x = [for (let x of N) if (x > 10) x * x];

P.S.: details:

Set builder notation

In Math: (sounds as: "Build me a set consisting of squares of numbers from the natural numbers set, but only if a number is greater than 10")

x = {x · x | x ∈ N ^ x > 10}

In programming languages:

Erlang

X = [X * X | X <- N, X > 10]

Python

x = [x * x for x in N if x > 10]

JavaScript 1.8 (before ES6)

var  x = [x * x for each (x in N) if (x > 10)];

Previous ECMAScript 6 proposal

let x = [x * x for x of N if x > 10];

ECMAScript 6 (current): swapped parts to look it similar to simple for-loop

let x = [for (let x of N) if (x > 10) x * x];

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment