XVal List comprehensions

List comprehensions can be used for mapping, filtering, folding, and scanning.

[ a + 5 | a <- [1,2,3] ]

Returns: [ 6,7,8 ]

Explanation: “a+5 where a drawn from [1,2,3]”. Loops over the list [1,2,3], assigns each value to the variable a, calculates a + 5, and emits to the output list.

[ a | a <- [1,2,3,4,5,6 ], a >= 4 ]

Returns: [ 4,5,6 ]

Explanation: “a where a drawn from [1,2,3,4,5,6] and a >= 4”. Loops over the list [1,2,3], assigns each value to the variable a, and emits to the output list if a is larger or equal to 4.

Syntax:

  • [ (state-variable: initial-state ->) expression | binding <- list-expression (, test-expression) ]

  • ( (state-variable: initial-state ->) expression | binding <- list-expression (, test-expression) )

Using state-variable one can transfer the result of each evaluation of expression over to the next evaluation. state-variable is visible during the evaluation of expression.

Using () brackets instead of [] returns only the last computed expression, instead of a list of every computation. This results in list folding instead of list scanning.

Examples

Sum a list of numbers

(s:0 -> x+s | x <- [1,2,3,4])

Result: 10

Return a running sum of numbers

[s:0 -> x+s | x <- [1,2,3,4]]

Result: [1,3,6,10]

Return a running sum of numbers larger than 1

[s:0 -> x+s | x <- [1,2,3,4], x > 1]

Result: [2,5,9]

Pick the last element that matches a condition

Or return the default state if none are found.

(s:-1 -> x < 3 && x || s | x <- [1,2,3,4])

Result: 2

Pick elements that match a condition

[x | x <- data, x.Name = ‘A’ || x.Name = ‘C’]

where data = [ { Name:”A”, Value: 1}, { Name: “B”, Value: 2}, { Name: “C”, Value: 3} ]Result: [ { Name:”A”, Value: 1}, { Name: “C”, Value: 3} ]

Last updated

Was this helpful?