List comprehensions

From Rosetta Code
Revision as of 22:57, 9 March 2008 by rosettacode>Kevin Reid (add E example)
Task
List comprehensions
You are encouraged to solve this task according to the task description, using any language you may know.

A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.

Write a list comprehension that builds the list of all pythagorean triples with elements between 1 and n. If the language has multiple ways for expressing such a construct (for example, direct list comprehensions and generators), write one example for each.

E

pragma.enable("accumulator") # considered experimental

accum [] for x in 1..n { for y in x..n { for z in y..n { if (x**2 + y**2 <=> z**2) { _.with([x,y,z]) } } } }

Erlang

 pythag(N) ->
     [ {A,B,C} ||
         A <- lists:seq(1,N),
         B <- lists:seq(1,N),
         C <- lists:seq(1,N),
         A+B+C =< N,
         A*A+B*B == C*C
     ].

Haskell

pyth n = [(x,y,z) | x <- [1..n], y <- [x..n], z <- [y..n], x^2 + y^2 == z^2]

Since lists are Monads, one can alternatively also use the do-notation (which is practical if the comprehension is large):

 import Control.Monad

 pyth n = do
   x <- [1..n]
   y <- [x..n]
   z <- [y..n]
   guard $ x^2 + y^2 == z^2
   return (x,y,z)

Python

[(x,y,z) for x in xrange(1,21) for y in xrange(x,21) for z in xrange(y,21) if x**2 + y**2 == z**2]

TODO: Alternative with generators