3.3 Partial Function and Curry - Gaoey/scala-diary GitHub Wiki

Partial Application :.

The process of applying a function to some of its arguments. The partially applied function gets returned for later use. In other words, a function that takes a function with multiple parameters and returns a function with fewer parameters. Partial application fixes (partially applies the function to) one or more arguments inside the returned function, and the returned function takes the remaining parameters as arguments in order to complete the function application.

partial application คือเทคนิคการแปลง function ที่มี argument หลายตัว - และ return function ที่มี argument น้อยกว่า

Example

def add(i: Int, j: Int) = i + j

// มี argument หลายตัว
// วิธีใช้ ให้บาง argument มีค่าใส่ไปก่อน ในที่นี้คือ 5
val add5 = add(_: Int,5) 

// function ที่มี argument น้อยกว่า
scala> add5(2)
res3: Int = 7

Curry :.

Currying is converting a single function of n arguments into n functions with a single argument

Curry คือ การแปลง function ที่มี n argument ไปเป็น จำนวน n function ที่แต่ละfunction มี argument เดียว (A,B) => C แปลงเป็น A => B => C

#javascript

// Normal function
function addition(x, y) {
   return x + y;
}

// Curried function
function addition(x) {
   return function(y) {
     return x + y;
   }
}

curry จะคล้ายๆกับหลักการของ function composition,

e.g., c(x) = f(g(x)).

Function composition takes the return value of one function and feeds it in as an argument to another function. Since a function can only return one value, the function being applied to the return value must be unary.


ข้อแตกต่าง

  • partial application จะคืนค่า function ที่มี argument น้อยกว่า original function - เพื่อให้ function มี argument น้อยลง
  • partial application ไม่สามารถคาร์ดการณ์ type ที่ return ได้ว่าจะเป็นอะไร.
  • curry function จะคืนค่า ฟังก์ชันที่เป็น unary function (function ที่มี argument เพียงตัวเดียว) เสมอ - มีจุดประสงค์เพื่อทำ generic function หรือ function ที่ reuse ได้บ่อยๆ
  • partial applicaiton ไม่ใช่ curry function

ซึ่ง curry จะดีมากๆ เพราะเราสามารถเชื่อถือ type ที่ return มาได้เสมอ (function type uniformity) ยกตัวอย่าง curry ดีๆคือ Promise ใน JS หรือ Future ใน scala ไม่ว่าเราจะโยน function อะไรเข้าไป มันจะ return type Future หรือ Promise คืนมาเสมอ (เราเรียกวิธีการนี้อีกแบบว่า functor คือการครอบมันเพื่อที่จะแมพมันออกมา)