List comprehensions

From Reia

Jump to: navigation, search

List comprehensions are a simple, declarative way to build a list from one or more other lists. They can be used in lieu of things like map and filter, and are far more powerful.

Examples:

# Double all numbers in a list
>> [x * 2 | x in [1,2,3]]
=> [2,4,6]
# Convert all strings to upper case
>> [s.upcase() | s in ['cat', 'dog', 'rat']]
=> ["CAT","DOG","RAT"]
# Find all Pythagorean triples less than 50
>> n = 50
>> [(a,b,c) | a in 1..n, b in 1..n, c in 1..n, a+b+c <= n, a**2 + b**2 == c**2]
=> [(3,4,5),(4,3,5),(5,12,13),(6,8,10),(8,6,10),(8,15,17),(9,12,15),(12,5,13),...]
Personal tools