I have read quite a few articles on closures, and, embarassingly enough, I still don't understand this concept! Articles explain how to create a closure with a few examples, but I don't see any point in paying much attention to them, as they largely look contrived examples. I am not saying all of them are contrived, just that the ones I found looked contrived, and I dint see how even after understanding them, I will be able to use them. So in order to understand closures, I am looking at a few real problems, that can be solved very naturally using closures.
For instance, a natural way to explain recursion to a person could be to explain the computation of n!. It is very natural to understand a problem like computing the factorial of a number using recursion. Similarly, it is almost a no-brainer to find an element in an unsorted array by reading each element, and comparing with the number in question. Also, at a different level, doing Object-oriented programming also makes sense.
So I am trying to find a number of problems that could be solved with or without closures, but using closures makes thinking about them and solving them easier. Also, there are two types to closures, where each call to a closure can create a copy of the environment variables, or reference the same variables. So what sort of problems can be solved more naturally in which of the closure implementations?
Callbacks are a great example. Let's take JavaScript.
Imagine you have a news site, with headlines and short blurbs and "Read More..." buttons next to each one. When the user clicks the button, you want to asynchronously load the content corresponding to the clicked button, and present the user with an indicator next to the requested headline so that the user can "see the page working at it".
function handleClickOnReadMore(element) {
// the user clicked on one of our 17 "request more info" buttons.
// we'll put a whirly gif next to the clicked one so the user knows
// what he's waiting for...
spinner = makeSpinnerNextTo(element);
// now get the data from the server
performAJAXRequest('http://example.com/',
function(response) {
handleResponse(response);
// this is where the closure comes in
// the identity of the spinner did not
// go through the response, but the handler
// still knows it, even seconds later,
// because the closure remembers it.
stopSpinner(spinner);
}
);
}
Alright, say you're generating a menu in, say, javascript.
var menuItems = [
{ id: 1, text: 'Home' },
{ id: 2, text: 'About' },
{ id: 3, text: 'Contact' }
];
And your creating them in a loop, like this:
for(var i = 0; i < menuItems.length; i++) {
var menuItem = menuItems[i];
var a = document.createElement('a');
a.href = '#';
a.innerHTML = menuItem.text;
// assign onclick listener
myMenu.appendChild(a);
}
Now, for the onclick listener, you might attempt something like this:
a.addEventListener('click', function() {
alert( menuItem.id );
}, false);
But you'll find that this will have every link alert '3'. Because at the time of the click, your onclick code is executed, and the value of menuItem is evaluated to the last item, since that was the value it was last assigned, upon the last iteration of the for loop.
Instead, what you can do is to create a new closure for each link, using the value of menuItem as it is at that point in execution
a.addEventListener('click', (function(item) {
return function() {
alert( item.id );
}
})( menuItem ), false);
So what's going on here? We're actually creating a function that accepts item and then immediately call that function, passing menuItem. So that 'wrapper' function is not what will be executed when you click the link. We're executing it immediately, and assigning the returned function as the click handler.
What happens here is that, for each iteration, the function is called with a new value of menuItem, and a function is returned which has access to that value, which is effectively creating a new closure.
Hope that cleared things up =)
Personally I hated to write sort routines when I had a list of objects.
Usually you had the sort function and a separate function to compare the two objects.
Now you can do it in one statement
List<Person> fList = new List<Person>();
fList.Sort((a, b) => a.Age.CompareTo(b.Age));
Well, after some time, spent with Scala, I can not imagine a code, operating on some list without closures. Example:
val multiplier = (i:Int) => i * 2
val list1 = List(1, 2, 3, 4, 5) map multiplier
val divider = (i:Int) => i / 2
val list2 = List(1, 2, 3, 4, 5) map divider
val map = list1 zip list2
println(map)
The output would be
List((2,0), (4,1), (6,1), (8,2), (10,2))
I'm not sure, if it is the example, you are looking for, but I personally think, that best examples of closures's real power can be seen on lists-examples: all kinds of sortings, searchings, iterating, etc.
I personally find massively helpful presentation by Stuart Langridge on Closures in JavaScript (slides in pdf). It's full of good examples and a bit of sense of humour as well.
In C#, a function can implement the concept of filtering by proximity to a point:
IEnumerable<Point> WithinRadius(this IEnumerable<Point> points, Point c, double r)
{
return points.Where(p => (p - c).Length <= r);
}
The lambda (closure) captures the supplied parameters and binds them up into a computation that will performed at some later time.
Well, I use Closures on a daily basis in the form of a function composition operator and a curry operator, both are implemented in Scheme by closures:
Quicksort in Scheme for instance:
(define (qsort lst cmp)
(if (null? lst) lst
(let* ((pivot (car lst))
(stacks (split-by (cdr lst) (curry cmp pivot))))
(append (qsort (cadr stacks) cmp)
(cons pivot
(qsort (car stacks) cmp))))))
Where I cmp is a binary function usually applied as (cmp one two), I curried it in this case to split my stack in two by creating a unitary predicate if you like, my curry operators:
(define (curry f . args)
(lambda lst (apply f (append args lst))))
(define (curryl f . args)
(lambda lst (apply f (append lst args))))
Which respectively curry righthanded and lefthanded.
So currying is a good example of closures, another example is functional composition. Or for instance a function which takes list and makes from that a predicate that tests if its argument is a member of that list or not, that's a closure too.
Closure is one of the power strengths of JavaScript, because JavaScript is a lambda language. For more on this subject go here:
Trying to simplify some Javascript with closures
Related
We're in the process of converting our imperative brains to a mostly-functional paradigm. This function is giving me trouble. I want to construct an array that EITHER contains two pairs or three pairs, depending on a condition (whether refreshToken is null). How can I do this cleanly using a FP paradigm? Of course with imperative code and mutation, I would just conditionally .push() the extra value onto the end which looks quite clean.
Is this an example of the "local mutation is ok" FP caveat?
(We're using ReadonlyArray in TypeScript to enforce immutability, which makes this somewhat more ugly.)
const itemsToSet = [
[JWT_KEY, jwt],
[JWT_EXPIRES_KEY, tokenExpireDate.toString()],
[REFRESH_TOKEN_KEY, refreshToken /*could be null*/]]
.filter(item => item[1] != null) as ReadonlyArray<ReadonlyArray<string>>;
AsyncStorage.multiSet(itemsToSet.map(roArray => [...roArray]));
What's wrong with itemsToSet as given in the OP? It looks functional to me, but it may be because of my lack of knowledge of TypeScript.
In Haskell, there's no null, but if we use Maybe for the second element, I think that itemsToSet could be translated to this:
itemsToSet :: [(String, String)]
itemsToSet = foldr folder [] values
where
values = [
(jwt_key, jwt),
(jwt_expires_key, tokenExpireDate),
(refresh_token_key, refreshToken)]
folder (key, Just value) acc = (key, value) : acc
folder _ acc = acc
Here, jwt, tokenExpireDate, and refreshToken are all of the type Maybe String.
itemsToSet performs a right fold over values, pattern-matching the Maye String elements against Just and (implicitly) Nothing. If it's a Just value, it cons the (key, value) pair to the accumulator acc. If not, folder just returns acc.
foldr traverses the values list from right to left, building up the accumulator as it visits each element. The initial accumulator value is the empty list [].
You don't need 'local mutation' in functional programming. In general, you can refactor from 'local mutation' to proper functional style by using recursion and introducing an accumulator value.
While foldr is a built-in function, you could implement it yourself using recursion.
In Haskell, I'd just create an array with three elements and, depending on the condition, pass it on either as-is or pass on just a slice of two elements. Thanks to laziness, no computation effort will be spent on the third element unless it's actually needed. In TypeScript, you probably will get the cost of computing the third element even if it's not needed, but perhaps that doesn't matter.
Alternatively, if you don't need the structure to be an actual array (for String elements, performance probably isn't that critical, and the O (n) direct-access cost isn't an issue if the length is limited to three elements), I'd use a singly-linked list instead. Create the list with two elements and, depending on the condition, append the third. This does not require any mutation: the 3-element list simply contains the unchanged 2-element list as a substructure.
Based on the description, I don't think arrays are the best solution simply because you know ahead of time that they contain either 2 values or 3 values depending on some condition. As such, I would model the problem as follows:
type alias Pair = (String, String)
type TokenState
= WithoutRefresh (Pair, Pair)
| WithRefresh (Pair, Pair, Pair)
itemsToTokenState: String -> Date -> Maybe String -> TokenState
itemsToTokenState jwtKey jwtExpiry maybeRefreshToken =
case maybeRefreshToken of
Some refreshToken ->
WithRefresh (("JWT_KEY", jwtKey), ("JWT_EXPIRES_KEY", toString jwtExpiry), ("REFRESH_TOKEN_KEY", refreshToken))
None ->
WithoutRefresh (("JWT_KEY", jwtKey), ("JWT_EXPIRES_KEY", toString jwtExpiry))
This way you are leveraging the type system more effectively, and could be improved on further by doing something more ergonomic than returning tuples.
i learned about tuples today, in a nutshell they allow you to store several values, an example of tupel is
let exampleTuple = (exampleString: "This", exampleInt: 1)
And we can easily access any value of a tuple with a dot notation, for example:
exampleTuple.exampleString
To me this seems extremely similar to objects holding certain information, I might be missing something or not understanding tuples completely, therefore I'm asking for an explanation on when we should use tuples or objects?
According to the book on Swift,
Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures.
They define "temporary" through the scope of the data: if a piece of data never leaves the scope of a single method, or a group of methods of the same object, it can be considered temporary, even though it might very well persist through the lifetime of an application.
If your data structure is useful outside a temporary scope - for example, because it needs to be returned from a public method of your class, model it as a class or structure, rather than as a tuple.
Another important consideration is associating behavior with your data: if your object needs to have methods, use classes for them. Use tuples only for data devoid of behavior.
Tuples are heavily used in Python and it seems to me they have mostly the same purpose in Swift. Think of it as a quick way to deliver multiple values from one point to another. An example that shows up in the Swift book and a pattern that is used in Python very often is returning an HTTP status code and a text body from a method:
func greeting() {
return (200, "Hello World")
}
...
let (status, body) = greeting()
if 200 == status {
println(body)
}
else if status >= 400 {
println("Error \(status): \(body)")
}
Of course this is just one use case, but I think it gets the point across. A built-in example is the function enumerate(), which returns a tuple of (index, value):
for (idx, val) in enumerate(["a", "b", "c"]) {
println("Index \(idx): \(val)")
}
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4); // returns 7
var add3 = add(3); // returns a function
add3(4); // returns 7
The first statement returns 7, like the add(3, 4) statement.
The second statement defines a new function called add3 that will
add 3 to its argument. (This is what some may call a closure.)
The third statement uses the add3 operation to add 3 to 4, again
producing 7 as a result.
In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.
So how do you deal with something you'd naturally express as, say, f(x,y)? Well, you take that as equivalent to f(x)(y) -- f(x), call it g, is a function, and you apply that function to y. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).
As usual, wikipedia has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.
Here's a concrete example:
Suppose you have a function that calculates the gravitational force acting on an object. If you don't know the formula, you can find it here. This function takes in the three necessary parameters as arguments.
Now, being on the earth, you only want to calculate forces for objects on this planet. In a functional language, you could pass in the mass of the earth to the function and then partially evaluate it. What you'd get back is another function that takes only two arguments and calculates the gravitational force of objects on earth. This is called currying.
It can be a way to use functions to make other functions.
In javascript:
let add = function(x){
return function(y){
return x + y
};
};
Would allow us to call it like so:
let addTen = add(10);
When this runs the 10 is passed in as x;
let add = function(10){
return function(y){
return 10 + y
};
};
which means we are returned this function:
function(y) { return 10 + y };
So when you call
addTen();
you are really calling:
function(y) { return 10 + y };
So if you do this:
addTen(4)
it's the same as:
function(4) { return 10 + 4} // 14
So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:
let addTwo = add(2) // addTwo(); will add two to whatever you pass in
let addSeventy = add(70) // ... and so on...
Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things
1. cache expensive operations
2. achieve abstractions in the functional paradigm.
Imagine our curried function looked like this:
let doTheHardStuff = function(x) {
let z = doSomethingComputationallyExpensive(x)
return function (y){
z + y
}
}
We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:
let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)
We can get abstractions in a similar way.
Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.
For example, in F# you can define a function thus:-
let f x y z = x + y + z
Here function f takes parameters x, y and z and sums them together so:-
f 1 2 3
Returns 6.
From our definition we can can therefore define the curry function for f:-
let curry f = fun x -> f x
Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.
Using our previous example we can obtain a curry of f thus:-
let curryf = curry f
We can then do the following:-
let f1 = curryf 1
Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-
f1 2 3
Which returns 6.
This process is often confused with 'partial function application' which can be defined thus:-
let papply f x = f x
Though we can extend it to more than one parameter, i.e.:-
let papply2 f x y = f x y
let papply3 f x y z = f x y z
etc.
A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-
let f1 = f 1
f1 2 3
Which will return a result of 6.
In conclusion:-
The difference between currying and partial function application is that:-
Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-
let f x y z = x + y + z
let curryf = curry f
let f1 = curryf 1
let f2 = curryf 2
f1 2 3
6
f2 1 3
6
Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-
let f x y z = x + y + z
let f1 = f 1
let f2 = f 2
f1 2 3
6
f2 1 3
6
A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.
Currying means to convert a function of N arity into N functions of arity 1. The arity of the function is the number of arguments it requires.
Here is the formal definition:
curry(f) :: (a,b,c) -> f(a) -> f(b)-> f(c)
Here is a real world example that makes sense:
You go to ATM to get some money. You swipe your card, enter pin number and make your selection and then press enter to submit the "amount" alongside the request.
here is the normal function for withdrawing money.
const withdraw=(cardInfo,pinNumber,request){
// process it
return request.amount
}
In this implementation function expects us entering all arguments at once. We were going to swipe the card, enter the pin and make the request, then function would run. If any of those steps had issue, you would find out after you enter all the arguments. With curried function, we would create higher arity, pure and simple functions. Pure functions will help us easily debug our code.
this is Atm with curried function:
const withdraw=(cardInfo)=>(pinNumber)=>(request)=>request.amount
ATM, takes the card as input and returns a function that expects pinNumber and this function returns a function that accepts the request object and after the successful process, you get the amount that you requested. Each step, if you had an error, you will easily predict what went wrong. Let's say you enter the card and got error, you know that it is either related to the card or machine but not the pin number. Or if you entered the pin and if it does not get accepted you know that you entered the pin number wrong. You will easily debug the error.
Also, each function here is reusable, so you can use the same functions in different parts of your project.
Currying is translating a function from callable as f(a, b, c) into callable as f(a)(b)(c).
Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.
Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.
Currying doesn’t call a function. It just transforms it.
Let’s make curry function that performs currying for two-argument functions. In other words, curry(f) for two-argument f(a, b) translates it into f(a)(b)
function curry(f) { // curry(f) does the currying transform
return function(a) {
return function(b) {
return f(a, b);
};
};
}
// usage
function sum(a, b) {
return a + b;
}
let carriedSum = curry(sum);
alert( carriedSum(1)(2) ); // 3
As you can see, the implementation is a series of wrappers.
The result of curry(func) is a wrapper function(a).
When it is called like sum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
Then sum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.
Here's a toy example in Python:
>>> from functools import partial as curry
>>> # Original function taking three parameters:
>>> def display_quote(who, subject, quote):
print who, 'said regarding', subject + ':'
print '"' + quote + '"'
>>> display_quote("hoohoo", "functional languages",
"I like Erlang, not sure yet about Haskell.")
hoohoo said regarding functional languages:
"I like Erlang, not sure yet about Haskell."
>>> # Let's curry the function to get another that always quotes Alex...
>>> am_quote = curry(display_quote, "Alex Martelli")
>>> am_quote("currying", "As usual, wikipedia has a nice summary...")
Alex Martelli said regarding currying:
"As usual, wikipedia has a nice summary..."
(Just using concatenation via + to avoid distraction for non-Python programmers.)
Editing to add:
See http://docs.python.org/library/functools.html?highlight=partial#functools.partial,
which also shows the partial object vs. function distinction in the way Python implements this.
Here is the example of generic and the shortest version for function currying with n no. of params.
const add = a => b => b ? add(a + b) : a;
const add = a => b => b ? add(a + b) : a;
console.log(add(1)(2)(3)(4)());
Currying is one of the higher-order functions of Java Script.
Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.
Confused?
Let see an example,
function add(a,b)
{
return a+b;
}
add(5,6);
This is similar to the following currying function,
function add(a)
{
return function(b){
return a+b;
}
}
var curryAdd = add(5);
curryAdd(6);
So what does this code means?
Now read the definition again,
Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.
Still, Confused?
Let me explain in deep!
When you call this function,
var curryAdd = add(5);
It will return you a function like this,
curryAdd=function(y){return 5+y;}
So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script.
So come back to the currying,
This line will pass the second argument to the curryAdd function.
curryAdd(6);
which in turns results,
curryAdd=function(6){return 5+6;}
// Which results in 11
Hope you understand the usage of currying here.
So, Coming to the advantages,
Why Currying?
It makes use of code reusability.
Less code, Less Error.
You may ask how it is less code?
I can prove it with ECMA script 6 new feature arrow functions.
Yes! ECMA 6, provide us with the wonderful feature called arrow functions,
function add(a)
{
return function(b){
return a+b;
}
}
With the help of the arrow function, we can write the above function as follows,
x=>y=>x+y
Cool right?
So, Less Code and Fewer bugs!!
With the help of these higher-order function one can easily develop a bug-free code.
I challenge you!
Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.
Thanks, Have a nice day!
If you understand partial you're halfway there. The idea of partial is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.
In Clojure + is a function but to make things starkly clear:
(defn add [a b] (+ a b))
You may be aware that the inc function simply adds 1 to whatever number it's passed.
(inc 7) # => 8
Let's build it ourselves using partial:
(def inc (partial add 1))
Here we return another function that has 1 loaded into the first argument of add. As add takes two arguments the new inc function wants only the b argument -- not 2 arguments as before since 1 has already been partially applied. Thus partial is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.
Now imagine if the language were smart enough to understand introspectively that add wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define inc without explicitly using partial.
(def inc (add 1)) #partial is implied
This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.
Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.
The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.
The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.
For example:
function curryMinus(x)
{
return function(y)
{
return x - y;
}
}
var minus5 = curryMinus(1);
minus5(3);
minus5(5);
I can also do...
var minus7 = curryMinus(7);
minus7(3);
minus7(5);
This is very great for making complex code neat and handling of unsynchronized methods etc.
I found this article, and the article it references, useful, to better understand currying:
http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx
As the others mentioned, it is just a way to have a one parameter function.
This is useful in that you don't have to assume how many parameters will be passed in, so you don't need a 2 parameter, 3 parameter and 4 parameter functions.
As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js)
http://livescript.net/
times = (x, y) --> x * y
times 2, 3 #=> 6 (normal use works as expected)
double = times 2
double 5 #=> 10
In above example when you have given less no of arguments livescript generates new curried function for you (double)
A curried function is applied to multiple argument lists, instead of just
one.
Here is a regular, non-curried function, which adds two Int
parameters, x and y:
scala> def plainOldSum(x: Int, y: Int) = x + y
plainOldSum: (x: Int,y: Int)Int
scala> plainOldSum(1, 2)
res4: Int = 3
Here is similar function that’s curried. Instead
of one list of two Int parameters, you apply this function to two lists of one
Int parameter each:
scala> def curriedSum(x: Int)(y: Int) = x + y
curriedSum: (x: Int)(y: Int)Intscala> second(2)
res6: Int = 3
scala> curriedSum(1)(2)
res5: Int = 3
What’s happening here is that when you invoke curriedSum, you actually get two traditional function invocations back to back. The first function
invocation takes a single Int parameter named x , and returns a function
value for the second function. This second function takes the Int parameter
y.
Here’s a function named first that does in spirit what the first traditional
function invocation of curriedSum would do:
scala> def first(x: Int) = (y: Int) => x + y
first: (x: Int)(Int) => Int
Applying 1 to the first function—in other words, invoking the first function
and passing in 1 —yields the second function:
scala> val second = first(1)
second: (Int) => Int = <function1>
Applying 2 to the second function yields the result:
scala> second(2)
res6: Int = 3
An example of currying would be when having functions you only know one of the parameters at the moment:
For example:
func aFunction(str: String) {
let callback = callback(str) // signature now is `NSData -> ()`
performAsyncRequest(callback)
}
func callback(str: String, data: NSData) {
// Callback code
}
func performAsyncRequest(callback: NSData -> ()) {
// Async code that will call callback with NSData as parameter
}
Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.
Most of the examples in this thread are contrived (adding numbers). These are useful for illustrating the concept, but don't motivate when you might actually use currying in an app.
Here's a practical example from React, the JavaScript user interface library. Currying here illustrates the closure property.
As is typical in most user interface libraries, when the user clicks a button, a function is called to handle the event. The handler typically modifies the application's state and triggers the interface to re-render.
Lists of items are common user interface components. Each item might have an identifier associated with it (usually related to a database record). When the user clicks a button to, for example, "like" an item in the list, the handler needs to know which button was clicked.
Currying is one approach for achieving the binding between id and handler. In the code below, makeClickHandler is a function that accepts an id and returns a handler function that has the id in its scope.
The inner function's workings aren't important for this discussion. But if you're curious, it searches through the array of items to find an item by id and increments its "likes", triggering another render by setting the state. State is immutable in React so it takes a bit more work to modify the one value than you might expect.
You can think of invoking the curried function as "stripping" off the outer function to expose an inner function ready to be called. That new inner function is the actual handler passed to React's onClick. The outer function is a closure for the loop body to specify the id that will be in scope of a particular inner handler function.
const List = () => {
const [items, setItems] = React.useState([
{name: "foo", likes: 0},
{name: "bar", likes: 0},
{name: "baz", likes: 0},
].map(e => ({...e, id: crypto.randomUUID()})));
// .----------. outer func inner func
// | currying | | |
// `----------` V V
const makeClickHandler = (id) => (event) => {
setItems(prev => {
const i = prev.findIndex(e => e.id === id);
const cpy = {...prev[i]};
cpy.likes++;
return [
...prev.slice(0, i),
cpy,
...prev.slice(i + 1)
];
});
};
return (
<ul>
{items.map(({name, likes, id}) =>
<li key={id}>
<button
onClick={
/* strip off first function layer to get a click
handler bound to `id` and pass it to onClick */
makeClickHandler(id)
}
>
{name} ({likes} likes)
</button>
</li>
)}
</ul>
);
};
ReactDOM.createRoot(document.querySelector("#app"))
.render(<List />);
button {
font-family: monospace;
font-size: 2em;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:
public static class FuncExtensions {
public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
{
return x1 => x2 => func(x1, x2);
}
}
//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);
//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times
//with different input parameters.
int result = func(1);
"Currying" is the process of taking the function of multiple arguments and converting it into a series of functions that each take a single argument and return a function of a single argument, or in the case of the final function, return the actual result.
The other answers have said what currying is: passing fewer arguments to a curried function than it expects is not an error, but instead returns a function that expects the rest of the arguments and returns the same result as if you had passed them all in at once.
I’ll try to motivate why it’s useful. It’s one of those tools that you never realized you needed until you do. Currying is above all a way to make your programs more expressive - you can combine operations together with less code.
For example, if you have a curried function add, you can write the equivalent of JS x => k + x (or Python lambda x: k + x or Ruby { |x| k + x } or Lisp (lambda (x) (+ k x)) or …) as just add(k). In Haskelll you can even use the operator: (k +) or (+ k) (The two forms let you curry either way for non-commutative operators: (/ 9) is a function that divides a number by 9, which is probably the more common use case, but you also have (9 /) for a function that divides 9 by its argument.) Besides being shorter, the curried version contains no made-up parameter name like the x found in all the other versions. It’s not needed. You’re defining a function that adds some constant k to a number, and you don’t need to give that number a name just to talk about the function. Or even to define it. This is an example of what’s called “point-free style”. You can combine operations together given nothing but the operations themselves. You don’t have to declare anonymous functions that do nothing but apply some operation to their argument, because *that’s what the operations already are.
This becomes very handy with higher-order functions when they’re defined in a currying-friendly way. For instance, a curried map(fn, list) let’s you define a mapper with just map(fn) that can be applied it to any list later. But currying a map defined instead as map(list, fn) just lets you define a function that will apply some other function to a constant list, which is probably less generally useful.
Currying reduces the need for things like pipes and threading. In Clojure, you might define a temperature conversion function using the threading macro ->: (defn f2c (deg) (-> deg (- 32) (* 5) (/ 9)). That’s cool, it reads nicely left to right (“subtract 32, multiply by 5 and divide by 9.”) and you only have to mention the parameter twice instead of once for every suboperation… but it only works because -> is a macro that transforms the whole form syntactically before anything is evaluated. It turns into a regular nested expression behind the scenes: (/ (* (- deg 32) 5) 9). If the math ops were curried, you wouldn’t need a macro to combine them so nicely, as in Haskell let f2c = (subtract 32) & (* 5) & (/ 9). (Although it would admittedly be more idiomatic to use function composition, which reads right to left: (/ 9) . (* 5) . (subtract 32).)
Again, it’s hard to find good demo examples; currying is most useful in complex cases where it really helps the readability of the solution, but those take so much explanation just to get you to understand the problem that the overall lesson about currying can get lost in the noise.
There is an example of "Currying in ReasonML".
let run = () => {
Js.log("Curryed function: ");
let sum = (x, y) => x + y;
Printf.printf("sum(2, 3) : %d\n", sum(2, 3));
let per2 = sum(2);
Printf.printf("per2(3) : %d\n", per2(3));
};
Below is one of currying example in JavaScript, here the multiply return the function which is used to multiply x by two.
const multiply = (presetConstant) => {
return (x) => {
return presetConstant * x;
};
};
const multiplyByTwo = multiply(2);
// now multiplyByTwo is like below function & due to closure property in JavaScript it will always be able to access 'presetConstant' value
// const multiplyByTwo = (x) => {
// return presetConstant * x;
// };
console.log(`multiplyByTwo(8) : ${multiplyByTwo(8)}`);
Output
multiplyByTwo(8) : 16
I'm looking to call functions dynamically based on the contents found in an association list.
Here is an example in semi-pseudo-code. listOfFunctions would be passed to callFunctions.
listOfFunctions = [('function one', 'value one')
, ('function two', 'value two')
, ('function three', 'value three')]
callFunctions x = loop through functions
if entry found
then call function with value
else do nothing
The crux of the question is not looping through the list, rather, it's how to call a function once I have it's name?
Consider this use case for further clarification. You open the command prompt and are presented with the following menu.
1: Write new vHost file
2: Exit
You write the new vHost file and are not presented with a new menu
1: Enter new directive
2: Write file
3: Exit
You enter some new directives for the vHost and are now ready to write the file.
The program isn't going to blindly write each and every directive it can, rather, it will only write the ones that you supplied. This is where the association list comes in. Writing a giant if/then/else or case statement is madness. It would be much more elegant to loop through the list, look for which directives were added and call the functions to write them accordingly.
Hence, loop, find a function name, call said function with supplied value.
Thanks to anyone who can help out with this.
Edit:
Here is the solution that I've come up with (constructive critiques are always welcome).
I exported the functions which write the directives in an association list as every answer provided said that just including the function is the way to go.
funcMap = [("writeServerName", writeServerName)
,("writeServeralias", writeServerAlias)
,("writeDocRoot", writeDocRoot)
,("writeLogLevel", writeErrorLog)
,("writeErrorPipe", writeErrorPipe)
,("writeVhostOpen", writeVhostOpen)]
In the file which actually writes the hosts, that file is imported.
I have an association list called hostInfo to simulate some dummy value that would be gathered from an end-user and a function called runFunction which uses the technique supplied by edalorzo to filter through both the lists. By matching on the keys of both lists I ensure that the right function is called with the right value.
import Vhost.Directive
hostInfo = [("writeVhostOpen", "localhost:80")
,("writeServerName", "norics.com")]
runFunctions = [f val | (mapKey, f) <- funcMap, (key, val) <- hostInfo, mapKey == key]
You can simply include the function in the list directly; functions are values, so you can reference them by name in a list. Once you've got them out of the list, applying them is just as simple as func value. There's no need to involve their names at all.
Since I am farily new to Haskell I will risk that you consider my suggestion very naive, but anyways here it goes:
let funcs = [("sum", (+3),1),("product", (*3),2),("square", (^2),4)]
[f x | (name, f, x) <- funcs, name == "sum"]
I think it satisfies the requirements of the question, but perhaps what you intend is more sofisticated than what I can see with my yet limitted knowledge of Haskell.
It might be a bit of an overkill (I agree with ehird's reasoning) but you can evaluate a string with Haskell code by using the eval function in System.Eval.Haskell.
EDIT
As pointed out in the comments, hint is a better option for evaluating strings with Haskell expressions. Quoting the page:
This library defines an Interpreter monad. It allows to load Haskell modules, browse them, type-check and evaluate strings with Haskell expressions and even coerce them into values. The library is thread-safe and type-safe (even the coercion of expressions to values). It is, esentially, a huge subset of the GHC API wrapped in a simpler API. Works with GHC 6.10.x and 6.8.x
First we define our list of functions. This could be built using more machinery, but for the sake of example I just make one explicit list:
listOfFunctions :: [(Int, IO ())]
listOfFunctions = [(0, print "HI") -- notice the anonymous function
,(1, someNamedFunction) -- and something more traditional here
]
someNamedFunction = getChar >>= \x -> print x >> print x
Then we can select from this list however we want and execute the function:
executeFunctionWithVal :: Int -> IO ()
executeFunctionWithVal v = fromMaybe (return ()) (lookup v listOfFunctions)
and it works (if you import Data.Maybe):
Ok, modules loaded: Main.
> executeFunctionWithVal 0
"HI"
> executeFunctionWithVal 01
a'a'
'a'
Don't store the functions as strings, or rather, try storing the actual functions and then tagging them with a string. That way you can just call the function directly. Functions are first class values, so you can call the function using whatever name you assign it to.
I recently had the necessity of rewriting a javascript function in javascript, dynamically. The ease with which I did it, and how fun it was, astounded me.
Over here I've got some HTML:
<div id="excelExport1234"
onclick="if(somestuff) location.href='http://server/excelExport.aspx?id=56789&something=else'; else alert('not important');"
>Click here to export to excel</div>
And I couldn't change the outputted HTML, but I needed to add an extra parameter to that link. I started thinking about it, and realized I could just do this:
excelExport = $('excelExport1234');
if (needParam)
eval('excelExport.onclick = ' + excelExport.onclick.toString().replace("excelReport.aspx?id", "excelReport.aspx?extraParam=true&id") + ';');
else
eval('excelExport.onclick = ' + excelExport.onclick.toString().replace("extraParam=true&", "") + ';');
And it worked like a champ! excelExport.onclick returns a function object which I convert to a string, and do some string manip on. Since it's now in the form of "function() { ... }", I just go back and assign it to the onclick event of the dom object. It's a little ugly having to use eval, but AFAIK there isn't a javascript function constructor that can take a string of code and turn it into an object nicely.
Anyway, my point isn't that I'm super clever (I'm not), my point is that this is cool. And I know javascript isn't the only language that can do this. I've heard that lisp has had macros for years for this exact purpose. Except to really grok macros you need to really grok lisp, and I don't grok it, I just 'kind of get it'.
So my question is: In what other languages can you (easily) dynamically rewrite functions, and can you show me a simple example? I want to see where else you can do this, and how it's done!
(also, I have no idea what to tag this as, so I took random guesses)
LISP is the ultimate language at this. LISP functions are actual LISP lists, meaning you can manipulate LISP source code as if it were any other data structure.
Here's a very trivial example of how it works:
(define hi
(lambda () (display "Hello World\n")))
;; Displays Hello World
(hi)
(set! hi
(lambda () (display "Hola World\n")))
;; Displays Hola World
(hi)
This, however, is possible in any language where functions are first-class objects. One of the most interesting showcases of the power of this syntax for LISP is in its macro system. I really don't feel I could do the topic justice, so read these links if you're interested:
http://en.wikipedia.org/wiki/Macro_(computer_science)#Lisp_macros
http://cl-cookbook.sourceforge.net/macros.html
I guess it depends on what exactly you define as "easily dynamic rewriting". For example in .Net you have the Func type and lambdas which allows you to define functions as variables or as temporary anonymous functions eg.
int[] numbers = {1, 2, 3, 4, 5};
Func<int[], int> somefunc;
if (someCondition)
{
somefunc = (is => is.Sum());
} else {
somefunc = (is => is.Count());
}
Console.WriteLine(somefunc(numbers).ToString());
The above is a very contrived example of either counting the items in an array of integers or summing then using dynamically created functions subject to some arbitrary condition.
Note - Please don't point out that these things can be easily accomplished without lambdas (which they obviously can) I was simply trying to write a very simple example to demonstrate the concept in C#
Self-modifying code is also called degenerate code. This is generally considered a bad thing, and it used to be a goal of high-level languages to prevent it from being written easily.
This is from the wikipedia entry:
Self-modifying code is seen by some as a bad practice which makes code harder to read and maintain. There are however ways in which self modification is nevertheless deemed acceptable, such as when sub routine pointers are dynamically altered - even though the effect is almost identical to direct modification.
I think that it is the case in most of dynamic languages. Here is an example in Python
def f(x):
print x
def new_function(x): print "hello", x
f("world")
f = new_function
f("world")
The output is
world
hello world
I think that such technique should be used carefully
Scheme allows you to do that.
(define (salute-english name) (display "Hello ") (display name))
(define (salute-french nom) (display "Salut ") (display nom))
Now you redefine a fonction by assigning the salute variable to the right function, either salute-english or salute-french, like this:
(define salute salute-english)
(define (redefined-the-salute-function language)
(if (eq? language 'french)
(set! salute salute-french)
(set! salute salute-english)))
More generaly functional programming language allows you to do that or as functions are first class value. Functions can be manipulated, passed around, sometimes assigned to variables and so on. The list then include: Lisp, Scheme, Dylan, OCaml and SML. Some languages having first class functions includes Python, Ruby, Smalltalk and i think Perl.
Note that when you have an interactive language where you can interactively type your program, the redefinition of functions/methods must be possible: the REPL has to be able to do that, just in case you happen to retype the definition of an already defined functions.
I used to do this all the time in TCL, it was a breeze and worked wonderfully. I could investigate somethings interface over the network and then create a custom-made interface on the fly to access and control things. For example, you could make a custom SNMP interface from a generic SNMP library.
I haven't used it, but C# has some built-in support for generating it's own byte-code, which is fairly impressive.
I've done this sort of thing in C as well, but there it is non-portable and almost never worth the hassle. It is a technique used sometimes for "self-optimizing" code to generate the appropriate C function to optimally process a given data set.
You could do it in C++, but it wouldn't be easy, safe, or recommended.
Generate the text of the source code
invoke the compiler (fork & exec) to build a dynamic library. In gcc, you can pass the source code you want to compile on standard input, it doesn't have to be in a file.
Load the library (LoadLibrary() on windows, dlopen() on linux)
get a function pointer to whatever function you want (GetProcAddress() on windows, dlsym() on linux)
If you want to replace an existing function, if it's a virtual function you could modify the v-table to point to the new function (that part especially is a horrible idea fraught with peril). The location of the v-table or the format of it isn't part of the C++ standard, but all the toolchains I've used have been consistent within themselves, so once you figure out how they do it, it probably won't break.
Easy enough in Perl.
*some_func = sub($) {
my $arg = shift;
print $arg, "\n";
};
some_func('foo');
Re Sam Saffron's request:
*hello_world = sub() {
print "oops";
};
hello_world();
*hello_world = sub() {
print "hello world";
};
hello_world();
In PLSQL:
create or replace procedure test
as
begin
execute immediate '
create or replace procedure test2
as
begin
null;
end;
';
end;
/
Here's something else in Python (in addition to luc's answer), which I am not recommending, but just to show it - there is exec, which can execute a string which you could build to be whatever code...
I/O shown here is from a Python 2.5.2 interpreter session. Just some simple examples of constructing strings to execute from substrings (>>> is the interpreter prompt)...
>>> def_string = 'def my_func'
>>> param_string_1 = '():'
>>> param_string_2 = '(x):'
>>> do_string_1 = ' print "Do whatever."'
>>> do_string_2 = ' print "Do something with", x'
>>> do_string_3 = ' print "Do whatever else."'
>>> do_string_4 = ' print "Do something else with", x'
>>> def_1 = '\n'.join([def_string+param_string_1, do_string_1, do_string_3])
>>> print def_1
def my_func():
print "Do whatever."
print "Do whatever else."
>>> exec def_1
>>> my_func()
Do whatever.
Do whatever else.
>>> def_2 = '\n'.join([def_string+param_string_2, do_string_2, do_string_4])
>>> print def_2
def my_func(x):
print "Do something with", x
print "Do something else with", x
>>> exec def_2
>>> my_func('Tom Ritter')
Do something with Tom Ritter
Do something else with Tom Ritter
>>>
Trivial in Ruby:
def hello_world; puts "oops"; end
hello_world
# oops
def hello_world; puts "hello world"; end
hello_world
# hello world
Of course that example is boring:
require "benchmark"
# why oh _why
class Object
def metaclass; class << self; self; end; end
def meta_eval &blk; metaclass.instance_eval &blk; end
end
class Turtle
end
def make_it_move(klass)
klass.send(:define_method, :move) { |distance|
puts "moving #{distance} meters"
sleep(0.1 * distance)
}
end
make_it_move(Turtle)
turtle = Turtle.new
turtle.move(1)
# moving 1 meters
def profile(instance, method)
instance.meta_eval do
m = instance_method(method)
define_method method do |*a|
puts "Benchmarking #{instance.class} #{method}"
puts Benchmark.measure {
m.bind(instance).call(*a)
}
end
end
end
profile(turtle, :move)
turtle.move(10)
# Benchmarking Turtle move
# moving 10 meters
# 0.000000 0.000000 0.000000 ( 1.000994)
Turtle.new.move(3)
# moving 3 meters
The code above:
Defines a blank class
Adds a method to it
Grabs an instance
Intercepts that method on that instance only
Changing what a function does is supported in a lot of languages, and it's not as complicated as you might think. In functional languages, functions are values, and function names are symbols that are bound to them like any variable. If the language allows you to reassign the symbol to a different function, this is trivial.
I think the more interesting features are the ability to get the source code for a function (toString above) and to create a new function from a string (eval in this case).