Contents
Comprehensions
Introduction
Overview
Strict Comprehensions
Lazy Comprehensions

Introduction

This article discusses comprehensions in Ela.

Overview

Ela supports list comprehensions in Haskell style (with slightly different syntax). Comprehensions can be used to produce both strict and lazy lists.

Strict Comprehensions

Comprehension consists of three parts - a value to select, an expression that actually fetches a value and an optional condition (guard clause). Let's say that we have a range [1..10] and we need to select all even integers from it, multiply each element by two and compile a new list with the result:
[x * 2 \\ x <- [1..10] | x % 2 == 0] //The result is: [4,8,12,16,20]
Guard clause is not mandatory and can be omitted:
[x * 2 \\ x <- [1..10]] //The result is: [2,4,6,8,10,12,14,16,18,20]
You can generate a list based on several inputs like so:
[x * y \\ x <- [10,9..1], y <- [1..10] | x % 2 == 0 && x > 5]
/*
The result is:
[10,20,30,40,50,60,70,80,90,100,8,16,24,32,40,48,56,64,72,80,6,12,18,24,30,36,42,48,54,60]
*/
Guards can be attached to each selector in comprehension. You can also use pattern matching in selectors and reference names declared in preceding selectors:
[x * y \\ x <- [10,9..1] | x % 2 == 0, y <- [x..10] | y > 5]
/*
The result is:
[100,64,72,80,36,42,48,54,60,24,28,32,36,40,12,14,16,18,20]
*/

Lazy Comprehensions

Comprehensions can be used to generate lazy lists. In this case a comprehension should start with an ampresand character &:
[& x \\ x <- [1..]]
Lazy comprehensions support the same features as strict comprehensions.