Common Lisp references to functions - function

There seems to be a number of different ways of referring to a function in Common Lisp:
via symbol, where the symbol appears (unquoted) as the car of a form as in (1+ 2) => 3, or in a functional argument position as in (mapcar '1+ '(1 2 3)) => (2 3 4);
via function object, where the (interpreted or compiled) function object can appear in functional argument position as in (mapcar #'1+ '(1 2 3)) => (2 3 4) or (mapcar (symbol-function '1+) '(1 2 3)) => (2 3 4), but not as the car of a form as in (#'1+ 2) => error or ((symbol-function '1+) 2) => error;
via lambda expression, where the lambda expression appears as the car of a lambda form as in ((lambda (x) (1+ x)) 2) => 3, or in a functional argument position as in (mapcar (lambda (x) (1+ x)) '(1 2 3)) => (2 3 4) [However, the Hyperspec does not recognize lambda expression as a "function designator"].
Of these three "ways", to me the first seems somewhat out of place, because it seems to complicate the fundamental guideline that Common Lisp operators evaluate their arguments only once. And if, in the example above, '1+ is evaluated, it would produce the symbol 1+, not the function named by the symbol. In this case, there must be an additional evaluation, possibly symbol-function, to get at the function object. Evidently, this is simply a convenience, but it seems to break with consistency. (The consistent form #'1+ is almost as simple.) My question is 'Are there any examples where using a symbol for a function is required (other than as the car of a form--although even this is not required, given lambda expressions), so that you cannot fully avoid expressions as in item 1 above?.

Symbols as names for objects: Designators
Often symbols are names for objects and can be used instead of these objects.
The concept that something like a symbol (or a string, a character) may stand for something else is called in Common Lisp a designator.
Some example for designators:
Function designator:
(funcall 'list 1 2 3)
<->
(funcall (symbol-function 'list) 1 2 3)
Class, or symbol that names a class:
(make-instance 'my-class)
<->
(make-instance (find-class 'my-class))
Package designator:
(package-use-list 'cl-user)
<->
(package-use-list (find-package 'cl-user))
<->
(package-use-list "CL-USER")
String designator:
(string-upcase 'f)
<->
(string-upcase (symbol-name 'f))
<->
(string-upcase #\f)
The first argument to FUNCALL thus is not defined as a function, but as a function designator. In this case either a function object or a symbol. If it is a symbol, then the global symbol function is retrieved.
Historically Lisp uses symbols as names for various kinds of objects. This is less prominent in some later dialects or derived languages.
function object vs. calling a named function vs. calling a symbol function
...(funcall (function foo) 1 2 3)...
...(funcall #'foo 1 2 3)...
Above calls the lexical function named foo. If there is no lexical function foo, it calls the symbol function of foo. The Lisp file compiler may assume that this is the same named function in the same file.
...(foo 1 2 3)...
Above calls the lexical function named foo. If there is no lexical function foo, it calls the symbol function of foo. The Lisp file compiler may assume that this is the same named function in the same file.
...(funcall 'foo 1 2 3)...
Above calls the global symbol function of foo. Thus there will be a lookup through the symbol.

Related

Is it possible to check/get function type or its signature at runtime in SBCL/Common Lisp?

(deftype binary-number-func ()
`(function (number number) number))
(declaim (ftype binary-number-func my-add))
(defun my-add (a b)
(+ (the number a) (the number b)))
;; FAIL:
(assert (typep #'my-add 'binary-number-func))
;; Function types are not a legal argument to TYPEP:
;; (FUNCTION (NUMBER NUMBER) (VALUES NUMBER &REST T))
;; [Condition of type SIMPLE-ERROR]
;; FAIL:
(typep #'my-add '(function (number number) number))
;; Function types are not a legal argument to TYPEP:
;; (FUNCTION (NUMBER NUMBER) (VALUES NUMBER &REST T))
;; [Condition of type SIMPLE-ERROR]
Is there any way to check the compound type of a function value?
(In Common Lisp, I'm using SBCL sbcl-1.5.0-x86-64-linux)
Thanks in advance.
Because Common Lisp allows you to write functions even if the compiler can’t determine a smallest function type for them, the compiler is not always able to check if a function has a certain type. Therefore the only sane behaviour is to not check the type.
Secondarily, such a minimal type may not exist. Consider this function:
(defun foo (key)
(getf '(:red 1 :blue 2 :green 3 :yellow 4) key))
Does it have type (function (T) T) or (function (T) (or null (integer 1 4))) or (function ((member :red :blue :green :yellow)) (integer 1 4)). Note in both the second and third types are correct but one is not a subtype of the other.
Also note that to check the third type above, one would need to precisely know the behaviour of getf which is unlikely to be true in this case and won’t be true at all in the general case.
It is ok for the compiler to check function types because the compiler is allowed to complain or give up. It would be completely unportable for different implementations to have runtime type checking functions which would have quite different behaviours.

How are functions defined in Scheme?

According to my assignment, some of the values ​​defined below in Scheme-notation are functions. I need to determine the value if it is not a function. Otherwise, I have to determine what the function calculates.:
First: (define res (+ 1 1))
Second: (define res2 ((lambda (i) (* wert1 i)) 2))
Now as far as I am concerned, the + is the functions name and the values 1,1 are the parameters of the function. Same for the seconds case. Lambda is a way to write functions in Scheme, isn't it? So I thought this must be a function too.
My solutions says that both are not functions but values!
Did I get something wrong or do my solutions have a twist?
You're right that + and (lambda (i) ...) are functions. However that wasn't the question. The question was whether the defined values (i.e. res and res2) are functions.
res is defined to be equal to (+ 1 1), which calls the + function with the arguments 1 1 (just as you said). The result of doing that is 2. So res is equal to 2, which is a number, not a function.
The same is true for the definition of res2: (lambda (i) (* wert1 i)) is a function. But you're not defining res2 to be equal to (lambda (i) (* wert1 i))1, you're defining it to be equal to the result of applying that function to the argument 2. So you're supposed to answer what the result of applying that function to that argument is.
1 That would look like this:
(define res3 (lambda (i) (* wert1 i)))
And in that case, "res3 is a function" would be the correct answer.

Choosing/evaluating macro argument forms

The Common Lisp case macro always defaults to eql for testing whether its keyform matches one of the keys in its clauses. I'm aiming with the following macro to generalize case to use any supplied comparison function (although with evaluated keys):
(defmacro case-test (form test &rest clauses)
(once-only (form test)
`(cond ,#(mapcar #'(lambda (clause)
`((funcall ,test ,form ,(car clause))
,#(cdr clause)))
`,clauses))))
using
(defmacro once-only ((&rest names) &body body)
"Ensures macro arguments only evaluate once and in order.
Wrap around a backquoted macro expansion."
(let ((gensyms (loop for nil in names collect (gensym))))
`(let (,#(loop for g in gensyms collect `(,g (gensym))))
`(let (,,#(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,#(loop for n in names for g in gensyms collect `(,n ,g)))
,#body)))))
For example:
(macroexpand '(case-test (list 3 4) #'equal
('(1 2) 'a 'b)
('(3 4) 'c 'd)))
gives
(LET ((#:G527 (LIST 3 4)) (#:G528 #'EQUAL))
(COND ((FUNCALL #:G528 #:G527 '(1 2)) 'A 'B)
((FUNCALL #:G528 #:G527 '(3 4)) 'C 'D)))
Is it necessary to worry about macro variable capture for a functional argument (like #'equal)? Can such arguments be left off the once-only list, or could there still be a potential conflict if #'equal were part of the keyform as well. Paul Graham in his book On Lisp, p.118, says some variable capture conflicts lead to "extremely subtle bugs", leading one to believe it might be better to (gensym) everything.
Is it more flexible to pass in a test name (like equal) instead of a function object (like #'equal)? It looks like you could then put the name directly in function call position (instead of using funcall), and allow macros and special forms as well as functions?
Could case-test instead be a function, instead of a macro?
Variable capture
Yes, you need to put the function into the once-only because it can be created dynamically.
The extreme case would be:
(defun random-test ()
(aref #(#'eq #'eql #'equal #'equalp) (random 4)))
(case-test foo (random-test)
...)
You want to make sure that the test is the same in the whole case-test form.
Name vs. object
Evaluating the test argument allows for very flexible forms like
(case-test foo (object-test foo)
...)
which allows "object-oriented" case-test.
Function vs. macro
Making case-test into a function is akin to making any other conditional (if and cond) into a function - how would you handle the proverbial
(case-test "a" #'string-equal
("A" (print "safe"))
("b" (launch missiles)))

Function application in Haskell

OK, it's been a long day and my brain may not function at Haskell level, but I just cannot understand one example from 'Learn You a Haskell'.
The section is called Function Application with $, and there is example of how $ may be defined:
($) :: (a -> b) -> a -> b
f $ x = f x
So far everything is clear. I understand all examples in the section, except for the last one:
ghci> map ($ 3) [(4+), (10*), (^2), sqrt]
[7.0,30.0,9.0,1.7320508075688772]
Here we map ($ 3) across list of functions and get result of application of those functions to 3. But how is this possible?
From the first code snippet it's clear that first argument is a function, we can even write:
*Main> ($) sqrt 4
2.0
Now ($ 3) is a partial application of function $, but 3 goes on function's position! So 3 is supposed to be a function or what?
There is another mystery: what the heck is (4+)? I know that (+4) is a partial application of function +, so (4+) should be partial application of function 4? Nonsense. What sort of trick works here?
($ 3) and (+ 4) aren't partial applications - they're operator sections. A partial application would look like (($) 3) or ((+) 4).
An operator section of the form (? x) (where ? stands for an arbitrary infix operator) binds the right operand of the operator, i.e. it is equivalent to \y -> y ? x. Likewise the operator section (x ?) binds the left operand and is thus equivalent to partial application.
I think what's tripping you up is operator sections. These let you partially apply an operator with either one of its arguments, so you can have the operators (+4) and (4+), where 4 is the the second then the first argument to + respectively. A more clear example might be ("Hello" ++) versus (++ "world"), the former prepends "Hello" onto the front of a string, while the latter appends "world" onto the end of a string.
This is contrasted with using operators in prefix form with just parens around it. In this form, the following are equivalent:
> let join = (++)
> join "Hello, " "world"
"Hello, world"
> (++) "Hello, " "world"
"Hello, world"
In prefix form, you treat the operator as a normal function and it accepts its first then second argument in order. In operator sections, it matters which side of the operator the argument is on.
So in your example, you have the partial application of ($ 3), you can reduce it as
map ($ 3) [(4+), (10*), (^2), sqrt]
[($ 3) (4+), ($ 3) (10 *), ($ 3) (^ 2), ($ 3) sqrt]
[4 + 3, 10 * 3, 3 ^ 2, sqrt 3]
[7.0, 30.0, 9.0, 1.7320508075688772]
You are getting confused with sections. A good way to grasp the concept of sections is playing with an example:
(<^>) :: Int -> Float -> Int
a <^> b = a
The above function is an useless function which returns the first parameter no matter what the second parameter is. But it accepts Int and then Float as input.
Now, because of sections you can apply with any one of their arguments:
λ> let a = (3 <^>)
λ> :t a
a :: Float -> Int
λ> let b = (<^> 3.0)
λ> :t b
b :: Int -> Int
See how the type of a and b are different because of sections.

What is the difference between currying and partial application?

I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.
I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.
Could someone provide me with a definition of both terms, and details of how they differ?
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 functional languages let you write f x y z. If you only call f x y or f(x)(y) then you get a partially-applied function—the return value is a closure of lambda(z){z(x(y))} with passed-in the values of x and y to f(x,y).
One way to use partial application is to define functions as partial applications of generalized functions, like fold:
function fold(combineFunction, accumulator, list) {/* ... */}
function sum = curry(fold)(lambda(accum,e){e+accum}))(0);
function length = curry(fold)(lambda(accum,_){1+accum})(empty-list);
function reverse = curry(fold)(lambda(accum,e){concat(e,accum)})(empty-list);
/* ... */
#list = [1, 2, 3, 4]
sum(list) //returns 10
#f = fold(lambda(accum,e){e+accum}) //f = lambda(accumulator,list) {/*...*/}
f(0,list) //returns 10
#g = f(0) //same as sum
g(list) //returns 10
The easiest way to see how they differ is to consider a real example. Let's assume that we have a function Add which takes 2 numbers as input and returns a number as output, e.g. Add(7, 5) returns 12. In this case:
Partial applying the function Add with a value 7 will give us a new function as output. That function itself takes 1 number as input and outputs a number. As such:
Partial(Add, 7); // returns a function f2 as output
// f2 takes 1 number as input and returns a number as output
So we can do this:
f2 = Partial(Add, 7);
f2(5); // returns 12;
// f2(7)(5) is just a syntactic shortcut
Currying the function Add will give us a new function as output. That function itself takes 1 number as input and outputs yet another new function. That third function then takes 1 number as input and returns a number as output. As such:
Curry(Add); // returns a function f2 as output
// f2 takes 1 number as input and returns a function f3 as output
// i.e. f2(number) = f3
// f3 takes 1 number as input and returns a number as output
// i.e. f3(number) = number
So we can do this:
f2 = Curry(Add);
f3 = f2(7);
f3(5); // returns 12
In other words, "currying" and "partial application" are two totally different functions. Currying takes exactly 1 input, whereas partial application takes 2 (or more) inputs.
Even though they both return a function as output, the returned functions are of totally different forms as demonstrated above.
Note: this was taken from F# Basics an excellent introductory article for .NET developers getting into functional programming.
Currying means breaking a function with many arguments into a series
of functions that each take one argument and ultimately produce the
same result as the original function. Currying is probably the most
challenging topic for developers new to functional programming, particularly because it
is often confused with partial application. You can see both at work
in this example:
let multiply x y = x * y
let double = multiply 2
let ten = double 5
Right away, you should see behavior that is different from most
imperative languages. The second statement creates a new function
called double by passing one argument to a function that takes two.
The result is a function that accepts one int argument and yields the
same output as if you had called multiply with x equal to 2 and y
equal to that argument. In terms of behavior, it’s the same as this
code:
let double2 z = multiply 2 z
Often, people mistakenly say that multiply is curried to form double.
But this is only somewhat true. The multiply function is curried, but
that happens when it is defined because functions in F# are curried by
default. When the double function is created, it’s more accurate to
say that the multiply function is partially applied.
The multiply function is really a series of two functions. The first
function takes one int argument and returns another function,
effectively binding x to a specific value. This function also accepts
an int argument that you can think of as the value to bind to y. After
calling this second function, x and y are both bound, so the result is
the product of x and y as defined in the body of double.
To create double, the first function in the chain of multiply
functions is evaluated to partially apply multiply. The resulting
function is given the name double. When double is evaluated, it uses
its argument along with the partially applied value to create the
result.
Interesting question. After a bit of searching, "Partial Function Application is not currying" gave the best explanation I found. I can't say that the practical difference is particularly obvious to me, but then I'm not an FP expert...
Another useful-looking page (which I confess I haven't fully read yet) is "Currying and Partial Application with Java Closures".
It does look like this is widely-confused pair of terms, mind you.
I have answered this in another thread https://stackoverflow.com/a/12846865/1685865 . In short, partial function application is about fixing some arguments of a given multivariable function to yield another function with fewer arguments, while Currying is about turning a function of N arguments into a unary function which returns a unary function...[An example of Currying is shown at the end of this post.]
Currying is mostly of theoretical interest: one can express computations using only unary functions (i.e. every function is unary). In practice and as a byproduct, it is a technique which can make many useful (but not all) partial functional applications trivial, if the language has curried functions. Again, it is not the only means to implement partial applications. So you could encounter scenarios where partial application is done in other way, but people are mistaking it as Currying.
(Example of Currying)
In practice one would not just write
lambda x: lambda y: lambda z: x + y + z
or the equivalent javascript
function (x) { return function (y){ return function (z){ return x + y + z }}}
instead of
lambda x, y, z: x + y + z
for the sake of Currying.
Currying is a function of one argument which takes a function f and returns a new function h. Note that h takes an argument from X and returns a function that maps Y to Z:
curry(f) = h
f: (X x Y) -> Z
h: X -> (Y -> Z)
Partial application is a function of two(or more) arguments which takes a function f and one or more additional arguments to f and returns a new function g:
part(f, 2) = g
f: (X x Y) -> Z
g: Y -> Z
The confusion arises because with a two-argument function the following equality holds:
partial(f, a) = curry(f)(a)
Both sides will yield the same one-argument function.
The equality is not true for higher arity functions because in this case currying will return a one-argument function, whereas partial application will return a multiple-argument function.
The difference is also in the behavior, whereas currying transforms the whole original function recursively(once for each argument), partial application is just a one step replacement.
Source: Wikipedia Currying.
Simple answer
Curry: lets you call a function, splitting it in multiple calls, providing one argument per-call.
Partial: lets you call a function, splitting it in multiple calls, providing multiple arguments per-call.
Simple hints
Both allow you to call a function providing less arguments (or, better, providing them cumulatively). Actually both of them bind (at each call) a specific value to specific arguments of the function.
The real difference can be seen when the function has more than 2 arguments.
Simple e(c)(sample)
(in Javascript)
We want to run the following process function on different subjects (e.g. let's say our subjects are "subject1" and "foobar" strings):
function process(context, successCallback, errorCallback, subject) {...}
why always passing the arguments, like context and the callbacks, if they will be always the same?
Just bind some values for the the function:
processSubject = _.partial(process, my_context, my_success, my_error)
// assign fixed values to the first 3 arguments of the `process` function
and call it on subject1 and foobar, omitting the repetition of the first 3 arguments, with:
processSubject('subject1');
processSubject('foobar');
Comfy, isn't it? 😉
With currying you'd instead need to pass one argument per time
curriedProcess = _.curry(process); // make the function curry-able
processWithBoundedContext = curriedProcess(my_context);
processWithCallbacks = processWithBoundedContext(my_success)(my_error); // note: these are two sequential calls
result1 = processWithCallbacks('subject1');
// same as: process(my_context, my_success, my_error, 'subject1');
result2 = processWithCallbacks('foobar');
// same as: process(my_context, my_success, my_error, 'foobar');
Disclaimer
I skipped all the academic/mathematical explanation. Cause I don't know it. Maybe it helped 🙃
EDIT:
As added by #basickarl, a further slight difference in use of the two functions (see Lodash for examples) is that:
partial returns a pre-cooked function that can be called once with the missing argument(s) and return the final result;
while curry is being called multiple times (one for each argument), returning a pre-cooked function each time; except in the case of calling with the last argument, that will return the actual result from the processing of all the arguments.
With ES6:
here's a quick example of how immediate Currying and Partial-application are in ECMAScript 6.
const partialSum = math => (eng, geo) => math + eng + geo;
const curriedSum = math => eng => geo => math + eng + geo;
The difference between curry and partial application can be best illustrated through this following JavaScript example:
function f(x, y, z) {
return x + y + z;
}
var partial = f.bind(null, 1);
6 === partial(2, 3);
Partial application results in a function of smaller arity; in the example above, f has an arity of 3 while partial only has an arity of 2. More importantly, a partially applied function would return the result right away upon being invoke, not another function down the currying chain. So if you are seeing something like partial(2)(3), it's not partial application in actuality.
Further reading:
Functional Programming in 5 minutes
Currying: Contrast with Partial Function Application
I had this question a lot while learning and have since been asked it many times. The simplest way I can describe the difference is that both are the same :) Let me explain...there are obviously differences.
Both partial application and currying involve supplying arguments to a function, perhaps not all at once. A fairly canonical example is adding two numbers. In pseudocode (actually JS without keywords), the base function may be the following:
add = (x, y) => x + y
If I wanted an "addOne" function, I could partially apply it or curry it:
addOneC = curry(add, 1)
addOneP = partial(add, 1)
Now using them is clear:
addOneC(2) #=> 3
addOneP(2) #=> 3
So what's the difference? Well, it's subtle, but partial application involves supplying some arguments and the returned function will then execute the main function upon next invocation whereas currying will keep waiting till it has all the arguments necessary:
curriedAdd = curry(add) # notice, no args are provided
addOne = curriedAdd(1) # returns a function that can be used to provide the last argument
addOne(2) #=> returns 3, as we want
partialAdd = partial(add) # no args provided, but this still returns a function
addOne = partialAdd(1) # oops! can only use a partially applied function once, so now we're trying to add one to an undefined value (no second argument), and we get an error
In short, use partial application to prefill some values, knowing that the next time you call the method, it will execute, leaving undefined all unprovided arguments; use currying when you want to continually return a partially-applied function as many times as necessary to fulfill the function signature. One final contrived example:
curriedAdd = curry(add)
curriedAdd()()()()()(1)(2) # ugly and dumb, but it works
partialAdd = partial(add)
partialAdd()()()()()(1)(2) # second invocation of those 7 calls fires it off with undefined parameters
Hope this helps!
UPDATE: Some languages or lib implementations will allow you to pass an arity (total number of arguments in final evaluation) to the partial application implementation which may conflate my two descriptions into a confusing mess...but at that point, the two techniques are largely interchangeable.
For me partial application must create a new function where the used arguments are completely integrated into the resulting function.
Most functional languages implement currying by returning a closure: do not evaluate under lambda when partially applied. So, for partial application to be interesting, we need to make a difference between currying and partial application and consider partial application as currying plus evaluation under lambda.
I could be very wrong here, as I don't have a strong background in theoretical mathematics or functional programming, but from my brief foray into FP, it seems that currying tends to turn a function of N arguments into N functions of one argument, whereas partial application [in practice] works better with variadic functions with an indeterminate number of arguments. I know some of the examples in previous answers defy this explanation, but it has helped me the most to separate the concepts. Consider this example (written in CoffeeScript for succinctness, my apologies if it confuses further, but please ask for clarification, if needed):
# partial application
partial_apply = (func) ->
args = [].slice.call arguments, 1
-> func.apply null, args.concat [].slice.call arguments
sum_variadic = -> [].reduce.call arguments, (acc, num) -> acc + num
add_to_7_and_5 = partial_apply sum_variadic, 7, 5
add_to_7_and_5 10 # returns 22
add_to_7_and_5 10, 11, 12 # returns 45
# currying
curry = (func) ->
num_args = func.length
helper = (prev) ->
->
args = prev.concat [].slice.call arguments
return if args.length < num_args then helper args else func.apply null, args
helper []
sum_of_three = (x, y, z) -> x + y + z
curried_sum_of_three = curry sum_of_three
curried_sum_of_three 4 # returns a function expecting more arguments
curried_sum_of_three(4)(5) # still returns a function expecting more arguments
curried_sum_of_three(4)(5)(6) # returns 15
curried_sum_of_three 4, 5, 6 # returns 15
This is obviously a contrived example, but notice that partially applying a function that accepts any number of arguments allows us to execute a function but with some preliminary data. Currying a function is similar but allows us to execute an N-parameter function in pieces until, but only until, all N parameters are accounted for.
Again, this is my take from things I've read. If anyone disagrees, I would appreciate a comment as to why rather than an immediate downvote. Also, if the CoffeeScript is difficult to read, please visit coffeescript.org, click "try coffeescript" and paste in my code to see the compiled version, which may (hopefully) make more sense. Thanks!
I'm going to assume most people who ask this question are already familiar with the basic concepts so their is no need to talk about that. It's the overlap that is the confusing part.
You might be able to fully use the concepts, but you understand them together as this pseudo-atomic amorphous conceptual blur. What is missing is knowing where the boundary between them is.
Instead of defining what each one is, it's easier to highlight just their differences—the boundary.
Currying is when you define the function.
Partial Application is when you call the function.
Application is math-speak for calling a function.
Partial application requires calling a curried function and getting a function as the return type.
A lot of people here do not address this properly, and no one has talked about overlaps.
Simple answer
Currying: Lets you call a function, splitting it in multiple calls, providing one argument per-call.
Partial Application: Lets you call a function, splitting it in multiple calls, providing multiple arguments per-call.
One of the significant differences between the two is that a call to a
partially applied function returns the result right away, not another
function down the currying chain; this distinction can be illustrated
clearly for functions whose arity is greater than two.
What does that mean? That means that there are max two calls for a partial function. Currying has as many as the amount of arguments. If the currying function only has two arguments, then it is essentially the same as a partial function.
Examples
Partial Application and Currying
function bothPartialAndCurry(firstArgument) {
return function(secondArgument) {
return firstArgument + secondArgument;
}
}
const partialAndCurry = bothPartialAndCurry(1);
const result = partialAndCurry(2);
Partial Application
function partialOnly(firstArgument, secondArgument) {
return function(thirdArgument, fourthArgument, fifthArgument) {
return firstArgument + secondArgument + thirdArgument + fourthArgument + fifthArgument;
}
}
const partial = partialOnly(1, 2);
const result = partial(3, 4, 5);
Currying
function curryOnly(firstArgument) {
return function(secondArgument) {
return function(thirdArgument) {
return function(fourthArgument ) {
return function(fifthArgument) {
return firstArgument + secondArgument + thirdArgument + fourthArgument + fifthArgument;
}
}
}
}
}
const curryFirst = curryOnly(1);
const currySecond = curryFirst(2);
const curryThird = currySecond(3);
const curryFourth = curryThird(4);
const result = curryFourth(5);
// or...
const result = curryOnly(1)(2)(3)(4)(5);
Naming conventions
I'll write this when I have time, which is soon.
There are other great answers here but I believe this example (as per my understanding) in Java might be of benefit to some people:
public static <A,B,X> Function< B, X > partiallyApply( BiFunction< A, B, X > aBiFunction, A aValue ){
return b -> aBiFunction.apply( aValue, b );
}
public static <A,X> Supplier< X > partiallyApply( Function< A, X > aFunction, A aValue ){
return () -> aFunction.apply( aValue );
}
public static <A,B,X> Function< A, Function< B, X > > curry( BiFunction< A, B, X > bif ){
return a -> partiallyApply( bif, a );
}
So currying gives you a one-argument function to create functions, where partial-application creates a wrapper function that hard codes one or more arguments.
If you want to copy&paste, the following is noisier but friendlier to work with since the types are more lenient:
public static <A,B,X> Function< ? super B, ? extends X > partiallyApply( final BiFunction< ? super A, ? super B, X > aBiFunction, final A aValue ){
return b -> aBiFunction.apply( aValue, b );
}
public static <A,X> Supplier< ? extends X > partiallyApply( final Function< ? super A, X > aFunction, final A aValue ){
return () -> aFunction.apply( aValue );
}
public static <A,B,X> Function< ? super A, Function< ? super B, ? extends X > > curry( final BiFunction< ? super A, ? super B, ? extends X > bif ){
return a -> partiallyApply( bif, a );
}
In writing this, I confused currying and uncurrying. They are inverse transformations on functions. It really doesn't matter what you call which, as long as you get what the transformation and its inverse represent.
Uncurrying isn't defined very clearly (or rather, there are "conflicting" definitions that all capture the spirit of the idea). Basically, it means turning a function that takes multiple arguments into a function that takes a single argument. For example,
(+) :: Int -> Int -> Int
Now, how do you turn this into a function that takes a single argument? You cheat, of course!
plus :: (Int, Int) -> Int
Notice that plus now takes a single argument (that is composed of two things). Super!
What's the point of this? Well, if you have a function that takes two arguments, and you have a pair of arguments, it is nice to know that you can apply the function to the arguments, and still get what you expect. And, in fact, the plumbing to do it already exists, so that you don't have to do things like explicit pattern matching. All you have to do is:
(uncurry (+)) (1,2)
So what is partial function application? It is a different way to turn a function in two arguments into a function with one argument. It works differently though. Again, let's take (+) as an example. How might we turn it into a function that takes a single Int as an argument? We cheat!
((+) 0) :: Int -> Int
That's the function that adds zero to any Int.
((+) 1) :: Int -> Int
adds 1 to any Int. Etc. In each of these cases, (+) is "partially applied".
Currying
Wikipedia says
Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument.
Example
const add = (a, b) => a + b
const addC = (a) => (b) => a + b // curried function. Where C means curried
Partial application
Article Just Enough FP: Partial Application
Partial application is the act of applying some, but not all, of the arguments to a function and returning a new function awaiting the rest of the arguments. These applied arguments are stored in closure and remain available to any of the partially applied returned functions in the future.
Example
const add = (a) => (b) => a + b
const add3 = add(3) // add3 is a partially applied function
add3(5) // 8
The difference is
currying is a technique (pattern)
partial application is a function with some predefined arguments (like add3 from the previous example)