JavaScript curry: what are the practical applications?

Here’s an interesting AND practical use of currying in JavaScript that uses closures: function converter(toUnit, factor, offset, input) { offset = offset || 0; return [((offset + input) * factor).toFixed(2), toUnit].join(” “); } var milesToKm = converter.curry(‘km’, 1.60936, undefined); var poundsToKg = converter.curry(‘kg’, 0.45460, undefined); var farenheitToCelsius = converter.curry(‘degrees C’, 0.5556, -32); milesToKm(10); // returns … Read more

Python Argument Binders

functools.partial returns a callable wrapping a function with some or all of the arguments frozen. import sys import functools print_hello = functools.partial(sys.stdout.write, “Hello world\n”) print_hello() Hello world The above usage is equivalent to the following lambda. print_hello = lambda *a, **kw: sys.stdout.write(“Hello world\n”, *a, **kw)

How does functools partial do what it does?

Roughly, partial does something like this (apart from keyword args support etc): def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper So, by calling partial(sum2, 4) you create a new function (a callable, to be precise) that behaves like sum2, but has one positional argument less. That missing argument is always … Read more

What is the difference between currying and partial application?

Currying is converting a single function of n arguments into n functions with a single argument each. Given the following function: function f(x,y,z) { z(x(y));} When curried, becomes: function f(x) { lambda(y) { lambda(z) { z(x(y)); } } } In order to get the full application of f(x,y,z), you need to do this: f(x)(y)(z); Many … Read more

Python: Why is functools.partial necessary?

What functionality does functools.partial offer that you can’t get through lambdas? Not much in terms of extra functionality (but, see later) – and, readability is in the eye of the beholder. Most people who are familiar with functional programming languages (those in the Lisp/Scheme families in particular) appear to like lambda just fine – I … Read more