Introduction
I've been doing a small Haskell project for the Uni and got really interested in this language and the Functional paradigm in general.
I suddenly felt like porting some of this cool functionality to Javascript.
Currying
I started by allowing functions to be curried. Here's a demo showing the script I made.
This is quite a fun way of making functions that derive from other functions.
Haskell functions
I then felt like porting Haskell's functions. Seemed doable considering Javascript has Higher Order Functions and we now can curry them.
I ported many Prelude's methods as well as Char methods.
Special features
Appart from currying, these functions can also work on strings, the same way as they do for lists (arrays). You don't need to worry about splitting(before) or joining(after). I added this because that's how Haskell's functions work.
These functions also work on maps/object/associative arrays. This might not be true for some functions where this was too complicated. This was the best adaptation of Haskell's Tuples that I could think of. A couple of functions like fst and snd don't have a concrete application for now.
In case I didn't make myself clear on this one, all the functions I made can be automatically curried. They're all contained in one namespace, that is, window.hs. I added a method called: hs.global() that will import all the functions to the global namespace. The magic currying function is available as hs.curry.
Operators
Haskell's operators are regular functions. I did imitate this adding most operators as methods. The only problem is that to reference them, you need to use something like hs['+'] instead of hs.+ as one would like.
To defeat this, I made hs a function, it provides a small shortcut for these cases. As an example: hs['+'](1,2) == hs('+',1,2).
I think the second option does look better. These functions can also be curried. hs._ will work the same as hs, but inverting the (2) arguments.
I added the dot operator for function composition, it's quite a powerful function.
That's it, the script is licensed under BSD, check the demo and play with it!

3 comments:
I've implemented currying somewhat differently for my projects:
function curry()
{
var args = jQuery.makeArray(arguments);
var fn = args.shift();
return function()
{
return fn.apply(this, args.concat(jQuery.makeArray(arguments)));
};
}
// example:
function add(x,y) { return x + y; }
var add1 = curry(add, 1);
alert(add1(2)); // alerts "3"
Hi Anton
That's pretty much the same I did. But yours can't be "chained".
For example:
add2 = add(2);
add5 = add2(3);
Curried functions also returned curried ones.
thanks! still learning this stuff
Post a Comment To get help prepare a demo.