Skip to content

Commit

Permalink
Update 2015-03-02-from-imperative-to-functional.md
Browse files Browse the repository at this point in the history
  • Loading branch information
jurgenvinju authored Jun 12, 2024
1 parent 687b7be commit 006d36f
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions blog/2015-03-02-from-imperative-to-functional.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The reason Rascal features these two styles is that we want to make it easy for
Let's write a function that generates all the even numbers in a list up to a certain maximum. We will do it in a few alternative
ways: from very imperative to very declarative and some steps in between.

```
```rascal
list[int] even0(int max) {
list[int] result = [];
for (int i <- [0..max])
Expand All @@ -24,7 +24,7 @@ list[int] even0(int max) {

Now lets remove the temporary type declarations:

```
```rascal
list[int] even1(int max) {
result = [];
for (i <- [0..max])
Expand All @@ -36,7 +36,7 @@ list[int] even1(int max) {

To make the code shorter, we can inline the condition in the for loop:

```
```rascal
list[int] even2(int max) {
result = [];
for (i <- [0..max], i % 2 == 0)
Expand All @@ -47,7 +47,7 @@ list[int] even2(int max) {

In fact, for loops may produce lists as values, using the append statement:

```
```rascal
list[int] even3(int max) {
result = for (i <- [0..max], i % 2 == 0)
append i;
Expand All @@ -57,7 +57,7 @@ list[int] even3(int max) {

So now, the result temporary is not necessary anymore:

```
```rascal
list[int] even4(int max) {
return for (i <- [0..max], i % 2 == 0)
append i;
Expand All @@ -66,21 +66,21 @@ list[int] even4(int max) {

This code is actually very close to a list comprehension already:

```
```rascal
list[int] even5(int max) {
return [ i | i <- [0..max], i % 2 == 0];
}
```

And now we can just define even using an expression only:

```
```rascal
list[int] even6(int max) = [i | i <- [0..max], i % 2 == 0];
```

Or, perhaps we like a set instead of a list:

```
```rascal
set[int] even7(int max) = {i | i <- [0..max], i % 2 == 0};
```

Expand Down

0 comments on commit 006d36f

Please sign in to comment.