Last active
March 7, 2016 08:46
-
-
Save zshell31/55bde73cbd14c8c9de48 to your computer and use it in GitHub Desktop.
Currying in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DEBUG = false; | |
var debug = function(msg) { | |
if (DEBUG) { | |
console.log(msg); | |
} | |
} | |
Function.prototype.curry = function() { | |
this.argList || (this.argList = []); | |
var newArgList = this.argList.concat(Array.prototype.slice.call(arguments, 0)); | |
var len = (this.len || this.length); | |
debug("arguments: " + newArgList + " ; len: " + len); | |
if (newArgList.length >= len) { | |
debug("apply"); | |
return this.apply(null, newArgList); | |
} | |
var self = this; | |
var fun = function() { | |
var res = self.apply(self, arguments); | |
debug("accessible len: " + len); | |
if (res.curry) { | |
debug("result is a function"); | |
var newArgs = Array.prototype.slice.call(arguments, len); | |
debug("new arguments: " + newArgs); | |
return res.curry.apply(res, newArgs); | |
} | |
debug("result is a scalar"); | |
return res; | |
}; | |
fun.len = len; | |
fun.argList = newArgList; | |
return fun; | |
} | |
var c = (x, y) => x; // Haskell: const = \x, y => x | |
var id = x => x // Haskell: id = \x => x | |
var snd = c.curry(id); // Haskell: snd = const id -- const id = (\x.\y.x) (\x.x) = \y.(\x.x) = \y.\x.x | |
// Example 1 | |
var f = snd.curry(1); // Haskell: f = snd 1 -- const id 1 = \y.\x.x 1 = \x.x = id | |
f.curry(3); // = f(3) = 3 | |
// Example 2 | |
snd.curry(1, 2); // = 2; Haskell: snd 1 2 = const id 1 2 = \y.\x.x 1 2 = \x.x 2 = 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment