module Array

from Microsoft.FSharp.Collections

An introduction to Higher Order Functions

@ReidNEvans

http://reidevans.tech

What is a Higher Order Function?

A function that accepts or returns a function

Good news! you've probably used them before

  • Map
  • Done
  • Then
  • Filter
  • Reduce
  • FlatMap

Map

  • Map
  • Select
  • fmap
  • array_map
1: 
2: 
3: 
4: 
5: 
6: 
['Hello', 'Tombras'].map(function(x) {
	return x.length
})

['Hello', 'Tombras'].map(x => x.length)
// [5,7]
1: 
2: 
3: 
// [string] -> (string -> number) -> [number]
['Hello', 'Tombras'].map(x => x.length)
// [5,7]
1: 
2: 
3: 
4: 
// [a] -> (a -> b) -> [b]
// [string] -> (string -> number) -> [number]
['Hello', 'Tombras'].map(x => x.length)
// [5,7]

Filter

  • Filter
  • Where
  • array_filter
1: 
2: 
['Hello', 'Tombras'].filter(x => x.length > 5)
// ['Tombras']
1: 
2: 
3: 
// [string] -> (string -> bool) -> [string]
['Hello', 'Tombras'].filter(x => x.length > 5)
// ['Tombras']
1: 
2: 
3: 
4: 
// [a] -> (a -> bool) -> [a]
// [string] -> (string -> bool) -> [string]
['Hello', 'Tombras'].filter(x => x.length > 5)
// ['Tombras']

Reduce

  • Reduce
  • Aggregate
  • fold
  • foldr
  • array_reduce
1: 
2: 
[1,2,3,4,5].reduce((accumulator, current) => accumulator + current)
//15
1: 
2: 
3: 
// [number] -> (number -> number -> number) -> number
[1,2,3,4,5].reduce((accumulator, current) => accumulator + current)
//15
1: 
2: 
3: 
4: 
// [a] -> (b -> a -> b) -> b
// [number] -> (number -> number -> number) -> number
[1,2,3,4,5].reduce((accumulator, current) => accumulator + current)
//15

FlatMap

  • Bind
  • SelectMany
  • >>=
1: 
2: 
['Hello', 'Tombras'].flatMap(x => x.split())
// ['H','e','l','l','o','T','o','m','b','r','a','s']
1: 
2: 
3: 
// [string] -> (string -> [string]) -> [string]
['Hello', 'Tombras'].flatMap(x => x.split())
// ['H','e','l','l','o','T','o','m','b','r','a','s']
1: 
2: 
3: 
4: 
// [a] -> (a -> [b]) -> [b]
// [string] -> (string -> [string]) -> [string]
['Hello', 'Tombras'].flatMap(x => x.split())
// ['H','e','l','l','o','T','o','m','b','r','a','s']

But wait, there's more!

1: 
2: 
3: 
$.get( "helloTombras.php" ).done(x => x.length);
// -------------------------------^
//12
1: 
2: 
3: 
//Deferred string -> (string -> number) -> Deferred number
$.get( "helloTombras.php" ).done(x => x.length);
//12
1: 
2: 
3: 
4: 
//Deferred a -> (a -> b) -> Deferred b
//Deferred string -> (string -> number) -> Deferred number
$.get( "helloTombras.php" ).done(x => x.length);
//12

Done

1: 
Deferred a -> (a -> b) -> Deferred b

Map

1: 
2: 
3: 
Array a -> (a -> b) -> Array b
or
[a] -> (a -> b) -> [b]