Difference Between Functions and Closures

What is the difference between functions and closures?

Functions are, in fact, just named closures. The following are at least conceptually equivalent:

let foo = { println("hello") }

func foo()->(){ println("hello") }

This gets a little more complicated in the case of using func to declare methods, as there's some interesting bits of sugar added regarding the automatic insertion of public named parameters, etc. func myMethod(foo:Int, bar:Int, baz:Int) becomes func myMethod(foo:Int, #bar:Int, #baz:Int), for example.

But it's still true that even methods are just a specific case of closures, and if it's true of closures, it's true of functions and methods as well.

Difference between Closure Functions and Functions

Closure:

  • Closure is a block of code, treat it like an unnamed function.
  • When a closure is passed as an argument, the closure is not evaluated till the code inside the function invokes the argument.

Auto closure:

  • Auto closure is just a closure which packages the parameter values along with it.
  • When you define an autoclosure, there would be no parameters to the closure.

Difference between fCheckGender and cCheckGender:

  • fCheckGender takes a String value as an argument.
  • cCheckGender takes closure as an argument.
  • When cCheckGender is invoked, the closure is passed an argument, at this point, the closure is only passed as an argument, the closure is not executed. Only when the closure parameter is used inside the function, the closure gets executed.

The example you have stated might not be the best one to demonstrate the difference.

Let's consider a different example:

Example:

func add(a: Int, b: Int) -> Int {

print("add")

return a + b
}

func f1(pValue: Int) {

print("f1")

print("value = \(pValue)")
}

func f2(pClosure: (Int, Int) -> Int, pA: Int, pB: Int) {

print("f2")

let value = pClosure(pA, pB)

print("value = \(value)")
}

//In autoclosure the closure always takes no parameters, because the closure is packaged with parameter values while invoking
func f3(pClosure: @autoclosure () -> Int) {

print("f3")

let value = pClosure()

print("value = \(value)")
}

f1(pValue: add(a: 10, b: 20))
print("=====================\n")

f2(pClosure: add, pA: 10, pB: 20)
print("=====================\n")

f3(pClosure: add(a: 10, b: 20))
print("=====================\n")

Output:

add
f1
value = 30
=====================

f2
add
value = 30
=====================

f3
add
value = 30
=====================

Explanation of example:

  • In the function f1 pValue is an Int value.
  • So when f1 is invoked, the add is evaluated
  • In the functions f2 and f3 pClosure is a closure.
  • pClosure (closure) is not evaluated till it is invoked inside the function.

Note:

  • Focus on f3 first which accepts a closure as the argument.
  • Once you fully understand f3, then examine f2.
  • Auto closure captures the parameter values when it is invoked and later uses it.

Why and when do we need to pass a closure instead of a value:

  • There might be a scenario, where you would like to defer the execution of add till the time the function f2 invokes it.
  • There might be a scenario, where you make an asynchronous request and you want a piece of code to execute when the request completes. In this case you might pass a closure. (Closure need not always return a value, it is an unnamed function, so it can accept parameters)

Why and when do we need to an autoclosure:

  • When you want to defer the execution of add and also capture the value of it's parameters.

Suggestion:

  • Though time consuming, it is best for you to go through the Swift documentation from the beginning to fully understand it.

Reference:

As Hamish has pointed please read about closures, then auto closures from https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Can anyone explain the difference between closure and nested functions?

One function written inside another function is called a nested function. Suppose that there are two functions outer function and inside it there is an inner function. The inner function will have access to its own variables, the outer functions variables, arguments and it has access to global variables. This is done by a scope chain. Every function so created has a scope chain associated with which helps us in accessing the variables value.

Now what are closures? Closures - the nested functions continue to live even when the outer function has completed is closure. The day to day way in which we are able to see closure is callbacks. Callbacks are functions which are usually executed when an event completes, when they are executed they have access to outer functions variables even though the outer function has completed its execution.

Can anyone explain the difference between closure and anonymous functions?

Have you seen this article? http://www.jibbering.com/faq/faq_notes/closures.html

This could also be good as a starting point: http://www.javascriptkit.com/javatutors/closures.shtml

Swift any difference between Closures and First-Class Functions?

These notions are orthogonal. They are not directly related; they are two facts about functions in Swift.

  • Functions are first-class. This means they can be passed around — assigned as variables, passed into function parameters as arguments, and passed out of functions as results.

  • Functions are closures. This means that, at the point of definition, they capture the environment referred to inside the function body but declared outside the function body.

Here is an example (from a playground):

func multiplierMaker(i:Int) -> (Int) -> (Int) {
func multiplier(ii:Int) -> (Int) {
return ii*i
}
return multiplier
}
let g = multiplierMaker(10)
g(2) // 20

Think about the function multiplier:

  • The fact that multiplier can be returned as the result of the function multiplierMaker, and assigned to g, and that it has a well-defined type (Int) -> (Int), is because functions are first-class.

  • The fact that, when 10 is passed into multiplierMaker, the resulting multiplier function multiplies its parameter by 10, even when assigned to g and called later, is because functions are closures.

(Notice that this has nothing to do with anonymous functions. All answers or statements leading you to believe that closures have to do with anonymous functions are wrong. There are no anonymous functions in this example. An anonymous function is a closure, but only because all functions are closures.)

Why the strong difference between closures and functions in Rust and how to work around it?

Currently, fn() types can be automatically "promoted" to || types. (A closure with an empty environment, I suppose.) For example, this works:

fn get(handler: || -> &str) -> &str {
handler()
}

fn main() {
fn handler_fn() -> &str { "handler_fn" }
let handler_cl = || -> &str "handler_cl";
println!("{}", get(handler_fn));
println!("{}", get(handler_cl));
}

So if your library function get doesn't care whether handler is a closure or not, then it seems reasonable to just accept closures for maximum flexibility. But this isn't always possible. For example, if you wanted to execute handler in another task, then I believe it must be a fn or a proc type. (I'm not 100% certain here---I may be missing a detail.)

With regard to anonymous functions, yes, a || or a proc closure are the only two ways to write anonymous functions.

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
def func(): return h
return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
def func(): return h
return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

Swift: definition and syntax of functions vs. closures

1: It's a closure.

Examples:

func aFunction() -> () {
// do something
}

let aClosure:() -> () = {
// do something
}

Functions are actually a special case of closures. You can write a
closure without a name by surrounding code with braces ({}). Use in to
separate the arguments and return type from the body.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

2: "in" is just the notation chosen to represent where the arguments/return type end, and the body of the closure begins. It has nothing to do with inout.



Related Topics



Leave a reply



Submit