Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

신나는 개발...

A Beginner’s Guide to Currying in Functional JavaScript 본문

weekly

A Beginner’s Guide to Currying in Functional JavaScript

벽돌1 2020. 4. 4. 00:11

https://www.sitepoint.com/currying-in-functional-javascript/

 

A Beginner's Guide to Currying in Functional JavaScript — SitePoint

M. David Green demonstrates the concept of currying — a useful technique, to partially evaluate functions and make your functional JavaScript more readable.

www.sitepoint.com

 

More Readable And More Flexible

One of the advantages touted for functional JavaScript is shorter, tighter code that gets right to the point in the fewest lines possible, and with less repetition. Sometimes this can come at the expense of readability; until you’re familiar with the way the functional programming works, code written in this way can be harder to read and understand.

 

FP스타일의 코드에 익숙하지ㅣ 않을 수 있지만 더 shorter하고 tight할 수 있다.

 

If you’ve come across the term currying before, but never knew what it meant, you can be forgiven for thinking of it as some exotic, spicy technique that you didn’t need to bother about. But currying is actually a very simple concept, and it addresses some familiar problems when dealing with function arguments, while opening up a range of flexible options for the developer.

 

예전에 currying을 맞딱들인 적이 있다면 하지만 이게 뭘 의미하는지 모를ㄴ다면, 너는 ~ 괜찮다.

 

What Is Currying?

Briefly, currying is a way of constructing functions that allows partial application of a function’s arguments. What this means is that you can pass all of the arguments a function is expecting and get the result, or pass a subset of those arguments and get a function back that’s waiting for the rest of the arguments. It really is that simple.

 

paramter하나짜리 함수를 3개로 쪼개고 이거를 조합해서 결과를 낸다.

a + b 하는 함수가 있다면 add(a, b)

fn = add(a)

fn.add(b)

add(a).add(b)

커링은 function을 일부 함수 인자에 대한 함수 인자의 일부 appllication을 생산하는 방시ㅣㄱ이다. 너는 함수가 기대하는 인자를 너는 패스할 수 있따.. 그릭고 결과를 얻을 수 있따. 그 인자의 ㅣ일부를 패스할 수 있고 나머지 인자를 기닫리는 함술를 다시 가질수이ㅣㅆ다.

 

Currying is elemental in languages such as Haskell and Scala, which are built around functional concepts. JavaScript has functional capabilities, but currying isn’t built in by default (at least not in current versions of the language). But we already know some functional tricks, and we can make currying work for us in JavaScript, too.

적어도 지금 버전에는 없다.

 

To give you a sense of how this could work, let’s create our first curried function in JavaScript, using familiar syntax to build up the currying functionality that we want. As an example, let’s imagine a function that greets somebody by name. We all know how to create a simple greet function that takes a name and a greeting, and logs the greeting with the name to the console:

var greet = function(greeting, name) {
  console.log(greeting + ", " + name);
};
greet("Hello", "Heidi"); //"Hello, Heidi"

 

 

This function requires both the name and the greeting to be passed as arguments in order to work properly. But we could rewrite this function using simple nested currying, so that the basic function only requires a greeting, and it returns another function that takes the name of the person we want to greet.

 

 

Our First Curry

var greetCurried = function(greeting) {
  return function(name) {
    console.log(greeting + ", " + name);
  };
};

 

This tiny adjustment to the way we wrote the function lets us create a new function for any type of greeting, and pass that new function the name of the person that we want to greet:

var greetHello = greetCurried("Hello");
greetHello("Heidi"); //"Hello, Heidi"
greetHello("Eddie"); //"Hello, Eddie"

 

We can also call the original curried function(greetCurried에 의해 뱉어진 함수...?) directly, just by passing each of the parameters in a separate set of parentheses, one right after the other:

 

Curry All the Things!

The cool thing is, now that we have learned how to modify our traditional function to use this approach for dealing with arguments, we can do this with as many arguments as we want:

이제 울리는 ~를 ㄹ배웠기 때문에 쿨한거ㅓㄴ 우리는 ~ 할숭ㅆ다는 거어ㅑ...

var greetDeeplyCurried = function(greeting) {
  return function(separator) {
    return function(emphasis) {
      return function(name) {
        console.log(greeting + separator + name + emphasis);
      };
    };
  };
};

 

We have the same flexibility with four arguments as we have with two. No matter how far the nesting goes, we can create new custom functions to greet as many people as we choose in as many ways as suits our purposes:

두개처럼 4개도 같은 유연함을 가진다.

var greetAwkwardly = greetDeeplyCurried("Hello")("...")("?");
greetAwkwardly("Heidi"); //"Hello...Heidi?"
greetAwkwardly("Eddie"); //"Hello...Eddie?"

 

What’s more, we can pass as many parameters as we like when creating custom variations on our original curried function, creating new functions that are able to take the appropriate number of additional parameters,

each passed separately in its own set of parentheses:

각각의 인자들은 각각 이것들으 ㅣ괄호 안에서 is passed

 

var sayHello = greetDeeplyCurried("Hello")(", ");
sayHello(".")("Heidi"); //"Hello, Heidi."
sayHello(".")("Eddie"); //"Hello, Eddie."

And we can define subordinate variations just as easily:

울리니ㅡㄴ 하위의 변화를ㄹ 쉽게 정의할 수 있다.

var askHello = sayHello("?");
askHello("Heidi"); //"Hello, Heidi?"
askHello("Eddie"); //"Hello, Eddie?"

 

각 변수들이 injection 당한거야.

 

Currying Traditional Functions

You can see how powerful this approach is, especially if you need to create a lot of very detailed custom functions. The only problem is the syntax. As you build these curried functions up, you need to keep nesting returned functions, and call them with new functions that require multiple sets of parentheses, each containing its own isolated argument. It can get messy.

각각 고립된 괄호를 포함하면서 새로운 함수는 다양한 괄호가 필요하다

 

To address that problem, one approach is to create a quick and dirty currying function that will take the name of an existing function that was written without all the nested returns. A currying function would need to pull out the list of arguments for that function, and use those to return a curried version of the original function:

 

var curryIt = function(uncurried) {
  var parameters = Array.prototype.slice.call(arguments, 1);
  return function() {
    return uncurried.apply(this, parameters.concat(
      Array.prototype.slice.call(arguments, 0)
    ));
  };
};

var greetGoodbye = curryIt(greeter, "Goodbye", ", ");
greetGoodbye(".", "Joe"); //"Goodbye, Joe."


var hi = curryIt("hi!");
curryIt(hi, 'a', 'b', 'c')

 

functor

monad

make promise