Pular para o conteúdo principal

Curry with JS

Partial application and currying with Javascript

In the strict way, currying is the technique of transforming a function that takes multiple arguments (a tuple of arguments) to one function that receive only one. In such way, currying techniques allow transform one multi-parameter function in a chain of functions, each one with a single argument. Looks complicated? Blah.. it is not true.
In this little article, we are actually more interesting in partial applications. Let’s take the Mozilla Example for replace function in String. As we know, we can use a “replacer” function as paramenter for replace method in String object.
Let’s say that we want to split a String defined by a non-numerical part, a numerical part and finally a non-alphanumeric part. Here is how:
function replacer(match, p1, p2, p3, offset, string){
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(' - ');
};
We can try it as usual…
var newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
So far so good. Let’s say now that the delimiter should change according with some conditions, e.g. locale specific.
function replacer(delimiter, match, p1, p2, p3, offset, string){
  return [p1, p2, p3].join(delimiter);
}
That’s bad. We cannot apply that replacer in regexp replace function. What can you do?
We want to have a partial application for that function. Take that!
function makeReplacer(delimiter) {
    return function replacer(match, p1, p2, p3, offset, string){
      return [p1, p2, p3].join(delimiter);
    }
}
So now, we can create a replacer for comma-separated-value:
var delimiter = ',';
var csvReplacer = makeReplacer(delimiter)
That constructor is so simple, so elementar that we could create a generic way to do that. Let’s create a curry function.
Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() { // new function
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };
How does the magic work? Closure!!! That dammit word is what defined the whole magic.
var fn = this;
var args = Array.prototype.slice.call(arguments);
First, arguments is a special object to access the parameters. However, arguments type is very similar to Array but it is not an Array. To use it in apply method we need to convert it to real Array. For that, we gonna use slice function. But slice function is a method defined on Array. Ok. Ok. Let’s use the slice function from Array replacing “this” object (within slice context) by “arguments” object. with the mighty call method…
Array.prototype.slice.call(arguments);
In that way, we have this and arguments saved on context. The Closure magic will keep that context (those local variables fn and args) within the context of new function. In that new function context, we also have a new values for this variable (now keeping the new function reference) and arguments (now the arguments of that function). So we can concat (add all elements) from arguments the to our args and we gonna have all arguments necessary for the original function.
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));};
So here we can rewrite the makeReplacer with curry… (because it is more spicy):
var delimiter = ',';
   var csvReplacer = replacer.curry(delimiter)

Comentários

balinjahmie disse…
Hard Rock Hotel Casino & Spa - Las Vegas, NV - Mapyro
The Hard Rock Hotel 밀양 출장샵 and Casino and Spa is an 부천 출장샵 on-site 보령 출장샵 casino and hotel located in Las Vegas, Nevada, 경기도 출장마사지 United States, 25 minutes away from McCarran International 양주 출장안마 Airport. Rating: 4.2 · ‎3,488 reviews

Postagens mais visitadas deste blog

Pequeno manual do ócio em terras alemãs

  Pequeno manual do ócio em terras alemãs Como Lei alemã favorece aproveitadoras (e alguns aproveitadores que nunca tive o desprazer de conhecer)   Há algumas vias pelas quais pessoas de países em desenvolvimento migram para países como a Alemanha.   Por exemplo, é sabido que países desenvolvidos sofrem de escassez de mão-de-obra qualificada. Por esse motivo, países como a Alemanha dispõe vistos "especiais" para profissionais em demanda. Esse é o conceito do Blaukart (Blue Card) que na Alemanha se destina a profissionais salário anual seja superior a 55 mil euros ou 43 mil no caso de profissionais de áreas em alta demanda. Não há como recrutar essa mão-de-obra sem que a família desses profissionais também possa ser relocada. Então esses profissionais e seus familiares são relocados.   Além de se qualificar para essas vagas em demanda, ou ser parte direta da família qualificada, outra via possível para a imigração para o território alemão é através do matrimôni

The escape of blue eyed vampires (answer)

The island of blue eyed vampires (answer) An initial idea Each one needs to figure out if him/herself is blue eyed. They assume having blue eyes and see how the others react. A technical details There are some variations to formalize this problem using different type of logic: modal logic, temporal logic, Public Announcement Logic and so on. I believe that those kind of prove are tedious to write and read. For now, I will write a sketch to a prove but I belive the best way to prove is using an algorimthm what basically, it would be an adaptation of DPLL algorithm (Davis–Putnam–Logemann–Loveland) that uses dedutive reasoning and prove by contraction. Legend \[\begin{matrix} BlueEyed(X) :X \text{ is blue eyed.} \\ Leave(X) :X \text{ leaves.} \\ O(y) :y \text{ holds at the next (temporal) state.} \end{matrix}\] In this temporal simplified logic, we have a set of state that holds the in- formation of days, \(W = \{d_0, d_1, d_2, d3 \ldots , d_n\}\) and transition \(S : W \rightarrow

Answering: top reasons I hate living in Brazil

Yes, some guys shared a teasing topic about “Top reasons why I hate living in Brazil”: http://www.gringoes.com/forum/forum_posts.asp?TID=17615&PN=1&title=top-reasons-i-hate-living-in-brazil What is the point here? The whole text is loaded of cliclés, people that you will hardly find, etc most of time just pissing people off.   I don’t think Brazil is the best country in the world. Also, I don’t think Brazilians don’t make mistakes. Actually we do all the time but most of us really care about our mistakes specially those were pointed out. Some feel like an expatriate, alien in own country. Others reflect about how we could improve. Others  simply don’t accept teases from John Does. So, I’m actually truly bothered with people believing in a bunch of false statements (specially Brazilians) or supporting some cynical arguments disguised “sincere” criticisms . Yes, I make mistakes all the time, and as most of Brazilians, I don’t speak English. However, I will