Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Marco Comini
2021-11-11
Higher-order: introduzione
Definizione
Una funzione di ordine superiore (o funzione higher-order) è una funzione che può
prendere altre funzioni come parametri e/o restituire funzioni come risultato.
Le variabili non-locali usate da una funzione restituita come parametro sono quelle
previste dallo scoping statico e continuano ad esistere anche se la funzione che le
aveva create è terminata?
1 var variable = " top - level " ;
2 function parentFunction () {
3 var variable = " local " ;
4 function childFunction () {
5 print ( " childFunction : variable = " + variable );
6 }
7 return childFunction ;
8 }
9
7 var strArr = [ " aa " , " bb " , " ccc " , " " , " dddd " ];
8 show ( strArr . find ( ( x )= > x . length >2 ));
9 show ( strArr . findIndex ( ( x )= > x . length >2 ));
Marco Comini Informatica Multimediale 2021-11-11 7 / 19
JavaScript: metodi di ordine superiore degli array/2
every( predicate )
Controlla se ogni elemento in un array soddisfa predicate
some( predicate )
Controlla se almeno uno degli elementi in un array soddisfa predicate
1 const f = ( x )= > x >= 2;
2 var numArr = [1 , 22 , 0 , 3];
3 show ( numArr . every ( f ));
4 show ( numArr . some ( f ));
filter( predicate )
Crea un nuovo array con ogni elemento in un array che soddisfa predicate
1 var numArr = [1 , 22 , 0 , 3];
2 show ( numArr . filter ( ( x )= > x >= 2 ));
3 var strArr = [ " aa " , " bb " , " ccc " , " " , " dddd " ];
4 show ( strArr . filter ( ( x )= > x . length >2 ));
map( function )
Crea un nuovo array con il risultato della chiamata di una funzione su ogni
elemento di un array
[v1 , . . . , vn ].reduce(f, x0 ) = xn
dove ∀1 ≤ i ≤ n. xi = f (xi−1 , vi )
Per esempio
1 function arraySum ( a ) {
2 return a . reduce ( (x , y )= > x +y , 0 );
3 }
[v1 , . . . , vn ].reduceRight(f, x0 ) = xn
Per esempio
1 function arraySum ( a ) {
2 return a . reduceRight ( (x , y )= > x +y , 0 );
3 }
✓
4 0, 1, 2