GDPR Cookie Consent by Free Privacy Policy Generator
post thumb
Asset Control
by Matthias Hanitzsch-Moonlight/ on 22 Mar 2019

A touch of functional programming with map()

Formula Engine - like many other programming languages - offers a map function. And while there are no lambdas, in many cases using map is more elegant than a for-loop.

Let’s look at an example:

acdba@acbox:~$ cat test.fe
function square(input) {
  return input*input;
}

return map(square, [1, 2, 3, 4, 5]);
acdba@acbox:~$ ac_evalform -f test.fe
1
4
9
16
25
acdba@acbox:~$ 

In the example above, map applies the given unary operation to each element in the given list.

But you can also use map to apply a binary operation to elements coming from two lists:

acdba@acbox:~$ cat test.fe
function add(a, b) {
  return a+b;
}

return map(add, [1, 2, 3, 4, 5], [3, 4, 5, 6, 7]);
acdba@acbox:~$ ac_evalform -f test.fe
4
6
8
10
12
acdba@acbox:~$ 

Maybe next time your fingers want to type for(i=0; ...), stop and consider whether map could do the same more elegantly.

comments powered by Disqus