Functional Programming explained to my grandma


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
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