Functional Programming explained to my grandma

CCavalier
3,733 views

Open Source Your Knowledge, Become a Contributor

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

Create Content

Higher Order Function

In functional programming, a function is defined as a "first order citizen". This means it includes all the properties generally available to any other element, such as the possibility of being affected to a name, returned as a result or passed as a parameter.

A higher-order function is a function that accepts other functions as parameters and/or use a function as the return value.
Let's try it out! Implement the greeting function to return "Hello, [name]" if the name is defined. Otherwise, return "who are you?".

More detailed informations

[Check the scaladoc!] (http://docs.scala-lang.org/tutorials/tour/higher-order-functions.html)

How to pass a function as a parameter?

def apply(f: Int => String, v: Int) = f(v)
Greetings
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
package example
object Hof{
/**
* return hello to someone
*/
def hello (string: String): String = {
"Hello, "+string
}
/**
* if string is not empty say something, else ask "Who are you"
*/
def greetings = ???
/**
* should say hello if string is empty, else ask "Who are you"
*/
def helloOrAskName(string: String): String = ???/*{
greetings(string, hello)
}*/
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

What make high order functions awesome is this ability to pass a function in parameter.

Let's try to implement the following example: we want to use different sorts. Let's try to use the already-implemented sort function to define the other ones.

_ Language tips _ For this example you can use the wildcard character _ which can match any parameter. It's useful to compare elements to each other.

Implement the differents sort
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
package example
/**
* Created by charlotte on 13/05/17.
*/
object HofSort {
def sort(cmp: (String, String)=>Boolean, list: List[String]):List[String] ={
list.sortWith(cmp)
}
def comparator(a: String, b: String): Boolean ={
if(a < b) true
else false
}
def sortAlphabetically(list: List[String]):List[String]= {
??? //TODO use the sort method with a function to comparate elements
}
def sortReverseAlphabetically(list: List[String]):List[String]={
??? //TODO use the sort method with a function to comparate elements
}
def sortIncreasingSize(list: List[String]):List[String]={
??? //TODO use the sort method with a function to comparate elements
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can use functions of the collection API the same way you use map and reduce.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content