### The Many Faces of a Sequence Comprehension

#### By Igor Geier on Jun 17, 2008

Last month I held a presentation about the JavaFX Script programming language. It was easy to impress the audience by showing how fast a graphical user interface can be done. Last year I worked as a teaching assistant for a Java course, where I had to use the Eclipse IDE. Due to not having a visual GUI editor, I spent a whole day preparing a simple Swing source code example (the students then used it for an exercise). In the JavaFX Script programming language the more intuitive way of writing (and reading) Swing applications is a great relief.

In the functional part of my presentation I used a sequence comprehension, similar to that I found in the draft language reference [1], in order to decide if a number is a prime number or not.

`for (i in [2..n/2] where n % i == 0) i`

*(1)*

It returns a sequence of factors of a natural number n, not including 1 and n, so that n is prime iff the sequence of factors is empty. In mathematics one could say, there is a corresponding set of factors of n denoted by

*n*/2],

*n*mod

*i*= 0}.

A sequence comprehension consists of three parts: a list of input sequences, a filter and an expression, which is "applied" to the filtered input. The expression in *(1)* is `i`

, so that just the identity function is applied to the filtered input. We get the same result by only filtering [2..n/2].

```
function filter ( lst : Integer []
```

, f : function(:Integer):Boolean ) : Integer [] {

var res : Integer [] = [];

for (i in lst) {

if (f(i)) {

insert i into res;

}

}

return res;

}

function factors (n : Integer) : Integer [] {

return filter( [2..n/2]

, function(i) { return n % i == 0; } );

}

Instead of defining a filter function, that takes a sequence and a predicate and returns a new sequence, we could use the built-in selection syntax.

`[2..n/2][i | n % i == 0]`

On the other hand, the filter function demonstrates the possibility of passing functions as arguments. The predicate passed by `factors`

is an anonymous function.

There is also an equivalent sequence comprehension for a sequence syntax without filtering. The filter has just to be always true.