20-CS-4003-001 Organization of Programming Languages Fall 2017
List Comprehensions

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Simple Examples of List Comprehensions

   
v1 = [ x | x <- [1,2,3,4,5,6]]  -  v1 is [1,2,3,4,5,6]
v2 = [ x | x <- [1..6]]  -  v2 is [1,2,3,4,5,6]
v3 = [ x+y | x <- [1..10] | y <- [2,4..16]]  -  v3 is [3,6,9,12,15,18,21,24] (list elements add)
v4 = [ x+y | x <- [2..4], y <- [1..2]]  -  v4 is [3,4,4,5,5,6] (add all pairs of x and y)
v5 = 1 : [ x+1 | x <- v5]  -  v5 is [1,2,3,4...] (starts with 1, next element increments...)
v6 = [ x+1 | x <- v6]  -  v6 goes crazy
v7 = [1]++[ x+1 | x <- v7]  -  v7 is [1,2,3,4...] (same as v5)
v8 = z where z = 1 : [ x+1 | x <- z]  -  v8 is [1,2,3,4...] (use of where)
v9 = [ (x,y) | x <- [1,2,3], y <- [2,4,6]]  -  v9 is [(1,2),(1,4),(1,6),(2,2),(2,4),(2,6),(3,2),(3,4),(3,6)]
v10 = [ x | x <- [1..10], odd x]  -  v10 is [1,3,5,7,9] (filtering)