Skip to content

Commit 006d36f

Browse files
authored
Update 2015-03-02-from-imperative-to-functional.md
1 parent 687b7be commit 006d36f

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

blog/2015-03-02-from-imperative-to-functional.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The reason Rascal features these two styles is that we want to make it easy for
1212
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
1313
ways: from very imperative to very declarative and some steps in between.
1414

15-
```
15+
```rascal
1616
list[int] even0(int max) {
1717
list[int] result = [];
1818
for (int i <- [0..max])
@@ -24,7 +24,7 @@ list[int] even0(int max) {
2424

2525
Now lets remove the temporary type declarations:
2626

27-
```
27+
```rascal
2828
list[int] even1(int max) {
2929
result = [];
3030
for (i <- [0..max])
@@ -36,7 +36,7 @@ list[int] even1(int max) {
3636

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

39-
```
39+
```rascal
4040
list[int] even2(int max) {
4141
result = [];
4242
for (i <- [0..max], i % 2 == 0)
@@ -47,7 +47,7 @@ list[int] even2(int max) {
4747

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

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

5858
So now, the result temporary is not necessary anymore:
5959

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

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

69-
```
69+
```rascal
7070
list[int] even5(int max) {
7171
return [ i | i <- [0..max], i % 2 == 0];
7272
}
7373
```
7474

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

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

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

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

0 commit comments

Comments
 (0)