Skip to content

Commit 051a818

Browse files
authored
Merge pull request #255 from longo-andrea/article/currying
Currying
2 parents 6d82644 + dd3cc70 commit 051a818

File tree

1 file changed

+52
-52
lines changed

1 file changed

+52
-52
lines changed

1-js/99-js-misc/03-currying-partials/article.md

Lines changed: 52 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@ libs:
55

66
# Currying
77

8-
[Currying](https://en.wikipedia.org/wiki/Currying) is an advanced technique of working with functions. It's used not only in JavaScript, but in other languages as well.
8+
Il [currying](https://en.wikipedia.org/wiki/Currying) è una tecnica avanzata che si applica alle funzioni. Non viene utilizzata solamente in JavaScript, ma anche in altri linguaggi di programmazione.
99

10-
Currying is a transformation of functions that translates a function from callable as `f(a, b, c)` into callable as `f(a)(b)(c)`.
10+
Il currying è una trasformazione che traduce una funzione invocabile come `f(a, b, c)` in una invocabile come `f(a)(b)(c)`.
1111

12-
Currying doesn't call a function. It just transforms it.
12+
Il currying non invoca la funzione. Si occupa solamente della sua trasformazione.
1313

14-
Let's see an example first, to better understand what we're talking about, and then practical applications.
14+
Come prima cosa vediamo un esempio, in modo da capire di cosa stiamo parlando, e le applicazioni nella pratica.
1515

16-
We'll create a helper function `curry(f)` that performs currying for a two-argument `f`. In other words, `curry(f)` for two-argument `f(a, b)` translates it into a function that runs as `f(a)(b)`:
16+
Creeremo una funzione di supporto `curry(f)` che esegue il currying per una funzione a due argomenti `f`. In altre parole, `curry(f)`, trasformerà `f(a, b)` in una funzione invocabile come `f(a)(b)`:
1717

1818
```js run
1919
*!*
20-
function curry(f) { // curry(f) does the currying transform
20+
function curry(f) { // curry(f) esegue il currying
2121
return function(a) {
2222
return function(b) {
2323
return f(a, b);
@@ -26,7 +26,7 @@ function curry(f) { // curry(f) does the currying transform
2626
}
2727
*/!*
2828

29-
// usage
29+
// utilizzo
3030
function sum(a, b) {
3131
return a + b;
3232
}
@@ -36,84 +36,84 @@ let curriedSum = curry(sum);
3636
alert( curriedSum(1)(2) ); // 3
3737
```
3838

39-
As you can see, the implementation is straightforward: it's just two wrappers.
39+
Come potete vedere, l'implementazione è piuttosto semplice: sono due semplici wrappers.
4040

41-
- The result of `curry(func)` is a wrapper `function(a)`.
42-
- When it is called like `curriedSum(1)`, the argument is saved in the Lexical Environment, and a new wrapper is returned `function(b)`.
43-
- Then this wrapper is called with `2` as an argument, and it passes the call to the original `sum`.
41+
- Il risultato di `curry(func)` è un wrapper `function(a)`.
42+
- Quando viene invocato come `curriedSum(1)`, l'argomento viene memorizzato nel Lexical Environment, e viene ritornato un nuovo wrapper `function(b)`.
43+
- Successivamente questo wrapper viene invocato con `2` come argomento, che passerà l'invocazione a `sum`.
4444

45-
More advanced implementations of currying, such as [_.curry](https://lodash.com/docs#curry) from lodash library, return a wrapper that allows a function to be called both normally and partially:
45+
Implementazioni più avanzate del currying, come [_.curry](https://lodash.com/docs#curry) fornito dalla libreria lodash, ritorna un wrapper che consente di invocare una funzione sia nella forma standard che in quella parziale:
4646

4747
```js run
4848
function sum(a, b) {
4949
return a + b;
5050
}
5151

52-
let curriedSum = _.curry(sum); // using _.curry from lodash library
52+
let curriedSum = _.curry(sum); // utilizzando _.curry della libreria lodash
5353

54-
alert( curriedSum(1, 2) ); // 3, still callable normally
55-
alert( curriedSum(1)(2) ); // 3, called partially
54+
alert( curriedSum(1, 2) ); // 3, riamane invocabile normalmente
55+
alert( curriedSum(1)(2) ); // 3, invocata parzialmente
5656
```
5757

58-
## Currying? What for?
58+
## Currying? Per quale motivo?
5959

60-
To understand the benefits we need a worthy real-life example.
60+
Per poterne comprendere i benefici abbiamo bisogno di un esempio di applicazione reale.
6161

62-
For instance, we have the logging function `log(date, importance, message)` that formats and outputs the information. In real projects such functions have many useful features like sending logs over the network, here we'll just use `alert`:
62+
Ad esempio, abbiamo una funzione di logging `log(date, importance, message)` che formatta e ritorna le informazioni. In un progetto reale, una funzione del genere ha diverse funzionalità utili, come l'invio di log in rete; qui useremo semplicemente un `alert`:
6363

6464
```js
6565
function log(date, importance, message) {
6666
alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
6767
}
6868
```
6969

70-
Let's curry it!
70+
Eseguiamo il currying!
7171

7272
```js
7373
log = _.curry(log);
7474
```
7575

76-
After that `log` works normally:
76+
Successivamente al `log`, funzionerà normalmente:
7777

7878
```js
7979
log(new Date(), "DEBUG", "some debug"); // log(a, b, c)
8080
```
8181

82-
...But also works in the curried form:
82+
...Ma funzionerà anche nella forma parziale:
8383

8484
```js
8585
log(new Date())("DEBUG")("some debug"); // log(a)(b)(c)
8686
```
8787

88-
Now we can easily make a convenience function for current logs:
88+
Ora possiamo creare una funzione utile per registrare i logs:
8989

9090
```js
91-
// logNow will be the partial of log with fixed first argument
91+
// logNow sarà la versione parziale di log con il primo argomento fisso
9292
let logNow = log(new Date());
9393

94-
// use it
94+
// utilizziamola
9595
logNow("INFO", "message"); // [HH:mm] INFO message
9696
```
9797

98-
Now `logNow` is `log` with fixed first argument, in other words "partially applied function" or "partial" for short.
98+
Ora `logNow` equivale a `log` con il primo argomento fissato, in altre parole, una "funzione applicata parzialmente" o "parziale" (più breve).
9999

100-
We can go further and make a convenience function for current debug logs:
100+
Possiamo anche andare oltre, e creare una funzione utile per registrare i logs di debug:
101101

102102
```js
103103
let debugNow = logNow("DEBUG");
104104

105105
debugNow("message"); // [HH:mm] DEBUG message
106106
```
107107

108-
So:
109-
1. We didn't lose anything after currying: `log` is still callable normally.
110-
2. We can easily generate partial functions such as for today's logs.
108+
Quindi:
109+
1. Non perdiamo nulla dopo il currying: `log` rimane invocabile normalmente.
110+
2. Possiamo generare molto semplicemente funzioni parziali per i logs quotidiani.
111111

112-
## Advanced curry implementation
112+
## Implementazione avanzata del currying
113113

114-
In case you'd like to get in to the details, here's the "advanced" curry implementation for multi-argument functions that we could use above.
114+
Nel caso in cui vogliate entrare più nel dettaglio, di seguito vediamo un'implementazione "avanzata" del currying per funzioni con più argomenti, che avremmo anche potuto usare sopra.
115115

116-
It's pretty short:
116+
E' piuttosto breve:
117117

118118
```js
119119
function curry(func) {
@@ -131,7 +131,7 @@ function curry(func) {
131131
}
132132
```
133133

134-
Usage examples:
134+
Esempi di utilizzo:
135135

136136
```js
137137
function sum(a, b, c) {
@@ -140,17 +140,17 @@ function sum(a, b, c) {
140140

141141
let curriedSum = curry(sum);
142142

143-
alert( curriedSum(1, 2, 3) ); // 6, still callable normally
144-
alert( curriedSum(1)(2,3) ); // 6, currying of 1st arg
145-
alert( curriedSum(1)(2)(3) ); // 6, full currying
143+
alert( curriedSum(1, 2, 3) ); // 6, ancora invocabile normalmente
144+
alert( curriedSum(1)(2,3) ); // 6, currying del primo argomento
145+
alert( curriedSum(1)(2)(3) ); // 6, currying completo
146146
```
147147

148-
The new `curry` may look complicated, but it's actually easy to understand.
148+
La funzione `curry` può sembrare complicata, ma in realtà è piuttosto semplice da capire.
149149

150-
The result of `curry(func)` call is the wrapper `curried` that looks like this:
150+
Il risultato dell'invocazione `curry(func)` è il wrapper `curried` (che ha subito il processo di currying), ed appare in questo modo:
151151

152152
```js
153-
// func is the function to transform
153+
// func è la funzione trasformata
154154
function curried(...args) {
155155
if (args.length >= func.length) { // (1)
156156
return func.apply(this, args);
@@ -162,27 +162,27 @@ function curried(...args) {
162162
};
163163
```
164164

165-
When we run it, there are two `if` execution branches:
165+
Quando la eseguiamo, ci sono due percorsi di esecuzione `if`:
166166

167-
1. If passed `args` count is the same or more than the original function has in its definition (`func.length`) , then just pass the call to it using `func.apply`.
168-
2. Otherwise, get a partial: we don't call `func` just yet. Instead, another wrapper is returned, that will re-apply `curried` providing previous arguments together with the new ones.
167+
1. Se il numero di `args` forniti è uguale o maggiore rispetto a quelli che la funzione originale ha nella sua definizione (`func.length`), allora gli giriamo semplicemente l'invocazione utilizzando `func.apply`.
168+
2. Altrimenti, otterremo un parziale: non invochiamo ancora `func`. Invece, viene ritornato un altro wrapper, che riapplicherà il `curried` passando gli argomenti precedenti insieme a quelli nuovi.
169169

170-
Then, if we call it, again, we'll get either a new partial (if not enough arguments) or, finally, the result.
170+
Quindi, se la invochiamo, di nuovo, avremo o una nuova funzione parziale (se non vengono forniti abbastanza argomenti) oppure otterremo il risultato.
171171

172-
```smart header="Fixed-length functions only"
173-
The currying requires the function to have a fixed number of arguments.
172+
```smart header="Solo funzioni di lunghezza fissa"
173+
Il currying richiede che la funzione abbia un numero fissato di argomenti.
174174
175-
A function that uses rest parameters, such as `f(...args)`, can't be curried this way.
175+
Una funzione che utilizza i parametri rest, come `f(...args)`, non può passare attraverso il processo di currying in questo modo.
176176
```
177177

178-
```smart header="A little more than currying"
179-
By definition, currying should convert `sum(a, b, c)` into `sum(a)(b)(c)`.
178+
```smart header="Un po' più del currying"
179+
Per definizione, il currying dovrebbe convertire `sum(a, b, c)` in `sum(a)(b)(c)`.
180180
181-
But most implementations of currying in JavaScript are advanced, as described: they also keep the function callable in the multi-argument variant.
181+
Ma la maggior parte delle implementazioni in JavaScript sono più avanzate di così, come descritto: queste mantengono la funzione invocabile nella variante a più argomenti.
182182
```
183183

184-
## Summary
184+
## Riepilogo
185185

186-
*Currying* is a transform that makes `f(a,b,c)` callable as `f(a)(b)(c)`. JavaScript implementations usually both keep the function callable normally and return the partial if the arguments count is not enough.
186+
Il *currying* è una trasformazione che rende `f(a,b,c)` invocabile come `f(a)(b)(c)`. Le implementazioni in JavaScript, solitamente, mantengono entrambe le varianti, sia quella normale che quella parziale, se il numero di argomenti non è sufficiente.
187187

188-
Currying allows us to easily get partials. As we've seen in the logging example, after currying the three argument universal function `log(date, importance, message)` gives us partials when called with one argument (like `log(date)`) or two arguments (like `log(date, importance)`).
188+
Il currying permette di ottenere delle funzioni parziali molto semplicemente. Come abbiamo visto nell'esempio del logging, dopo il currying la funzione universale a tre argomenti `log(date, importance, message)` ci fornisce una funzione parziale quando invocata con un solo argomento (come `log(date)`) o due argomenti (come `log(date, importance)`).

0 commit comments

Comments
 (0)