faculty
[cc1516.git] / examples / old / Markus / higher_order_functions.spl
1 // Depending on your design decisions this might or might not compile.
2 // In our course we don't require higher-order functions.
3 // In fact, our grammar doesn't even allow function types in type signatures.
4 // Anyway, this could be an idea for assignment 4.
5
6 map(f, list)
7 // This doesn't parse according to our grammar
8 // :: (a -> b) [a] -> [b]
9 {
10 if( isEmpty(list) )
11 return [];
12 else
13 return f(list.hd) : map(f, list.tl);
14 }
15
16 foldl(f, z, list)
17 {
18 if( isEmpty(list) )
19 return z;
20 else
21 return foldl(f, f(z, list.hd), list.tl);
22 }
23
24 // Some operators wrapped in a function.
25 plus(x, y) { return x + y; }
26 and(b, c) { return b && c; }
27 ge18(x) { return x >= 18; }
28
29 // Sums all the elements of an Int list.
30 sum(list) { return foldl(plus, 0, list); }
31
32 // Checks whether all elements in a list of Booleans are True
33 all(list) { return foldl(and, True, list); }
34
35 // Checks whether in a list of numbers everybody is older than 18
36 allOlderThan18(list) { return all(map(ge18, list)); }
37
38 main() { return; }