DAY 14
1
Software Development

# What’s currying?

Transforms a function with multiple arguments to a chain of function applications with one argument each

``````const add = (a, b) => a + b;
``````

``````const add = a => b => a + b;
``````
``````// ---- below is common way -------
``````

``````f = (a, b) => value
f(a, b)

// become currying
f = a => b => value
g = f(a); // return function b => value
g(b); // return value;

// 也可以
f(a)(b)
``````

# Why use currying?

• DRY (Don’t Repeat Yourself ): 有別於以往一個函式處理所有事情，Currying 可以將程式碼依功能拆解成更小單元，有助於重複利用 (這也是 FP 精華之一)
• 函式參數越多，處理程式碼時會更加繁複。currying 一次處理一個參數，提高程式的彈性和可讀性

``````const uncurriedGradeTest=(passGrade, failGrade, average, testScore) =>

// Repeat the same args many times
uncurriedGradeTest( 'Pass', 'Fail', 0.2, 0.19 )
uncurriedGradeTest( 'Pass', 'Fail', 0.2, 0.39 )
uncurriedGradeTest( 'Pass', 'Fail', 0.2, 0.5 )
uncurriedGradeTest( 'Pass', 'Fail', 0.2, 0.1 )
uncurriedGradeTest( 'Pass', 'Fail', 0.2, 0.8 )
``````

``````// Currying

const passFaillTest = getGradeTest( 'Pass', 'Fail' )( 0.2 );

passFaillTest( 0.19 )
passFaillTest( 0.39 )
passFaillTest( 0.5 )
passFaillTest( 0.1 )
passFaillTest( 0.8 )
``````

# Partial application vs. currying

``````// Currying
const add = a => b => c => a + b + c;
``````
``````// Partial application
const add = a => (b, c) => a + b + c;
``````
• currying: Creates a chain of unary functions
• Partial application: operates with functions of any arity
- currying Partial application
arity 1 variable (f, ...args)
bind arguments? No Yes

### Arity?

the number of arguments of a function

``````f( a ) // arity: 1
f( a, b ) // arity: 2
f(...args) // arity: 0
``````

## Partial application example

``````// partial Application
const partial =
(f, ...args1) =>
(...args2) =>
f(...args1 , ...args2);

const volume = (a, b c) => a*b*c;

console.log( partial( volume, 2, 3 )( 4 ) ) // 24
console.log( partial( volume, 2 )( 3, 4 ) ) // 24

f.bind(null, ...args)
``````

#### 參考文章

``````如有錯誤或需要改進的地方，拜託跟我說。

``````

### 1 則留言

0
ytyubox
iT邦新手 5 級 ‧ 2020-09-17 21:51:01