# Comprehensions in Julia

::

One of Haskell’s features that I really liked was list comprehensions, so I was very pleased to discover how nice Julia’s comprehensions are!

I was curious how they compared, so I went through “Chapter 5: List Comprehensions” in Graham Hutton’s “Programming Haskell” book. I think you’ll agree that Julia’s comprehensions compare favorably.

`[ x^2 | x <- [1..5] ]` `[ x^2 for x = 1:5 ]`
`[ (x,y) | x <- [1, 2, 3], y <- [4, 5] ]` `[ (x,y) for x = 1:3 for y = 4:5 ]`
`[ (x,y) | x <- [1..3], y <- [x..3 ]]` `[ (x,y) for x = 1:3 for y = x:3 ]`
`concat xss = [ x | xs <- xss, x <- xs ]` `concat(xss) = [ x for xs in xss for x in xs ]`
`firsts ps = [ x | (x,_) <- ps ]` `firsts(ps) = [ x for (x,_) in ps ]`
`length xs = sum[ 1 | _ <- xs ]` `length(xs) = sum(1 for _ in xs)`
`factors n = [ x | x <- [1..n], n `mod` x == 0 ]` `factors(n) = [ x for x = 1:n if n % x == 0 ]`
`prime n = factors n == [1, n]` `prime(n) = factors(n) == [1, n]`
`primes n = [ x | x <- [2..n], prime x ]` `primes(n) = [ x for x = 2:n if prime(x) ]`
`find k t = [ v | (k', v) <- t, k == k' ]` `find(k,t) = [ v for (k1,v) in t if k == k1 ]`
`pairs xs = zip xs (tail xs)` `pairs(xs) = zip(xs, xs[2:end])`
`sorted xs = and [x <= y | (x,y) <- pairs xs ]` `sorted(xs) = all(x <= y for (x,y) in pairs(xs))`
```positions x xs = [i | (x',i) <- zip xs [0..n], x == x']      where n = length xs - 1``` ```positions(x,xs) = [ i for (x1,i) in zip(xs, 1:(length(xs)))      if x == x1 ]```
```lowers xs = length [x | x <- xs, isLower x ]  ``` ```lowers(xs) = length([x for x in collect(xs)      if islowercase(x)])```
`count x xs = length [x' | x' <- xs, x == x']` `count(x,xs) = length([x1 for x1 in collect(xs) if x == x1])`