Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is currying just a way to avoid inheritance?

So my understanding of currying (based on SO questions) is that it lets you partially set parameters of a function and return a "truncated" function as a result.

If you have a big hairy function takes 10 parameters and looks like

function (location, type, gender, jumpShot%, SSN, vegetarian, salary) {
    //weird stuff
}

and you want a "subset" function that will let you deal with presets for all but the jumpShot%, shouldn't you just break out a class that inherits from the original function?

I suppose what I'm looking for is a use case for this pattern. Thanks!

like image 634
Alex Mcp Avatar asked Apr 27 '10 23:04

Alex Mcp


3 Answers

Currying has many uses. From simply specifying default parameters for functions you use often to returning specialized functions that serve a specific purpose.

But let me give you this example:

function log_message(log_level, message){}
log_error = curry(log_message, ERROR)
log_warning = curry(log_message, WARNING)

log_message(WARNING, 'This would be a warning')
log_warning('This would also be a warning')
like image 84
Wolph Avatar answered Nov 17 '22 00:11

Wolph


In javascript I do currying on callback functions (because they cannot be passed any parameters after they are called (from the caller)

So something like:

...
var test = "something specifically set in this function";
onSuccess: this.returnCallback.curry(test).bind(this),

// This will fail (because this would pass the var and possibly change it should the function be run elsewhere
onSuccess: this.returnCallback.bind(this,test),
...

// this has 2 params, but in the ajax callback, only the 'ajaxResponse' is passed, so I have to use curry
returnCallback: function(thePassedVar, ajaxResponse){
   // now in here i can have 'thePassedVar', if 
}

I'm not sure if that was detailed or coherent enough... but currying basically lets you 'prefill' the parameters and return a bare function call that already has data filled (instead of requiring you to fill that info at some other point)

like image 35
Mitch Dempsey Avatar answered Nov 17 '22 02:11

Mitch Dempsey


When programming in a functional style, you often bind arguments to generate new functions (in this example, predicates) from old. Pseudo-code:

filter(bind_second(greater_than, 5), some_list)

might be equivalent to:

filter({x : x > 5}, some_list)

where {x : x > 5} is an anonymous function definition. That is, it constructs a list of all values from some_list which are greater than 5.

like image 1
Steve Jessop Avatar answered Nov 17 '22 00:11

Steve Jessop