Functional Programming explained to my grandma
Anne-Honyme
13.7K views
Dummy example of lambda
Until now we have used a lot of functions. We specified that we want them to be pure (no side effect). We have seen that we can pass it as a parameter to other functions or use it in a return. Also, we have seen that by currying we can define precise functions that improve readability and reuse.
However, you will run into a function has no reason to be reused. In this case, we want to use it anonymously. This is what we call a lambda expression.
In this example, the operation function takes a function as a parameter and will apply it to each number from 1 to x, where x is the high limit parameter.
Let's try to use it to define three different functions:
- sum : a function to add each number from 1 to x
- sumSquare: a function to add each squared number from 1 to x
- sumPeer: a function to add the x first odd numbers
To complete these, let's use lambdas as the parameter of "operation"
Implement different sums
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package example
/**
* Created by charlotte on 13/05/17.
*/
object Lamdba {
/**
* will apply the f function to the a first integers
* @param a high limit
* @param f a function to apply
* @return the sum of the a first number where the f function has been applied
*/
def operation(a:Int)(f:(Int)=> Int): Int={
def opeAcc(acc : Int, lim: Int): Int={
if(lim == 0) acc
else opeAcc(acc + f(lim), lim -1)
}
opeAcc(0, a)
}
/**
* a function that will return the sum from 1 to a
*/
def sum(a : Int): Int = ???
/**
* a function that will return the sum of the square from 1 to a
*/
def sumSquare(a : Int): Int = ???
/**
* a function that will return the sum of the odd number from 1 to a
*/