Swift any difference between Closures and First-Class Functions? - swift

In the Swift documentation Apple says this:
Closures are self-contained blocks of functionality that can be passed
around and used in your code. Closures in Swift are similar to blocks
in C and Objective-C and to lambdas in other programming languages.
Which I thought was the definition of First-class functions
And they also say this:
Closures can capture and store references to any constants and
variables from the context in which they are defined. This is known as
closing over those constants and variables. Swift handles all of the
memory management of capturing for you.
I thought this was the definittion of closures while the other defitintion was for first-class functions, but Apple seems the put them together and call it closure.
Have I misunderstood something? or are Apple calling closures and first-class functions closures?
I've written this example code, and just wanna know if I'm right in the written comments?
// 'a' takes a first class function, which makes 'a' a higher order function
func a(ch: () -> Void){
print("Something")
ch() // 'ch' is a first class function
print("Ended")
}
func closureFunc(){
var num = 2
a({
// access to 'num' is possible by closures
num = num*2
print(num)
})
}
closureFunc()

A First Class Function is a language feature that allows a function that can be assigned to a variable and passed around as if it were any other kind of data. Closures, lambdas and anonymous functions are all "First class functions".
Anonymous Functions, also called Lambda functions, are functions that don't have a name (such as the way a(ch:) has a name). Because they don't have a name, the only way to use them is by storing them in a variable or passing them in as arguments (parameters are essentially variables). Thus all Anonymous functions are also First Class Functions.
Closures are first class functions that capture the state around them. They can be anonymous, or have a name. Named closures are just your regular func functions.
a(ch:) is a higher order function, correct.
ch is a First Class Function (as it's stored in a variable), a Lambda (synonymous with FCF) and possibly also a closure, depending on whether or not its body references any external variables.
In the case of a(ch:) being called with that block, ch is a closure, because it's capturing num.

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.)

Functions can capture variables in the context they were declared in, and "A combination of a function and an environment of captured variables is called - closure" more
Here is a simple explanation of closures and first class functions in Swift:
Functions are first class objects, they can be assigned to variables, they can be passed as arguments and can be returned
There are two ways of defining functions in Swift: one using the func keyword and using 'closure expressions' - (does not mean closures). e.g.
func f() { print("nothing") }
let a = f // cannot use parentheses here
// or using closure expression:
let a = { () -> void in print("nothing") }
And finally the direct answer to your question: Functions can capture variables in the context they were declared in, and "A combination of a function and an environment of captured variables is called - closure" e.g.
func f() -> ()->()
{
var c = 0 // local var
func innerf()
{
c += 1 // c is now captured
}
return innerf
} // normally c would be released here. but since its used in innerf(), it will stay
let f1 = f
Now we call f1 a closure because it captured a variable.

Related

Can you "apply" a function to a "package" of arguments in Swift somehow?

I was wondering if there's a function (or special syntax) which would behave something like the hypothetical apply below (but for arbitrary f; the one given here is just for the sake of example):
func f(a: String, b: String) -> Bool {
return a == b
}
let argDict = ["a": "foo", "b": "bar"]
apply(f, argDict) // evaluates f(a: "foo", b: "bar") and returns false
It doesn't have to use a dictionary for the arguments (maybe it even can't use a dictionary?); it could use some other datatype or even just some other special syntax, as long as it somehow enables you to package up arguments and then apply a function to them later, as though you had written the arguments in by hand.
If not for all functions, what about for special classes of functions, like functions with variadic arguments? For example, it would be nice to be able to apply a function with signature (Double...) -> Double to an array of type [Double] as though we had inlined the values.
And if it doesn't already exist as a built-in, can it be constructed?
(Also, I'm not looking to redefine f; if you wanted to, I think you could just redefine it via f1(dict: [String: String]) -> Bool { ... } and then use dict["a"] and dict["b"] in the body instead in place of a and b. But I'm asking this question because I'm curious about the language capabilities here, not because I'm trying to solve a specific problem.)
Swift used to have that. You could pass a tuple of the arguments rather than the arguments directly, which is exactly what you're describing (a strongly-typed argument package). It was called "tuple splat." It was removed in Swift 3. See the SE for the background and why it was removed.

When are Swift function default parameter values evaluated?

If I give a function parameter a default value that is a not a constant (e.g. the result of a function call) is that value just evaluated once (and if so, when?) or is it evaluated every time the function is called?
From The Swift Programming Language, under Language Reference > Declarations > Special Kinds of Parameters:
A parameter with an equals sign (=) and an expression after its type is understood to have a default value of the given expression. The given expression is evaluated when the function is called. If the parameter is omitted when calling the function, the default value is used instead.
You can demonstrate this for yourself by putting the following in a playground:
import Foundation
func foo(i: UInt32 = arc4random()) {
print(i)
}
foo()
foo()
foo()
foo()
foo()
which will print five different random numbers (unless the random number generator generates the same number five times by some astronomically improbable coincidence).
It's not explicit in the docs quoted above, so it's worth noting that when you do specify the argument when calling the function the default expression is not evaluated. You can demonstrate that in a playground too:
func getSomeInt() -> Int {
print("getSomeInt() was called")
return 42
}
func bar(_ i: Int = getSomeInt()) {
print(i)
}
bar(1)
and when that runs you'll see that "getSomeInt() was called" is not printed.

How can I have a function accepting a function which is the same type?

In swift, is it possible to have a function accepting another function of the same type as itself?
For example, I have this function in python:
lambda f: f(f)
How can I define a function like this in swift? And what will the type of f be?
From you question it sounds as if you're looking for a way to define the self-application combinator (/U combinator). I'm not certain it's possible to implement a U combinator behaviour in Swift, but you could, however, dwell down into the related fix-point combinator (/Y combinator) and recursive closures.
You can achieve the behaviour of the Y combinator by defining a function that takes a function to function higher order function as parameter, say f: (T->U) -> (T->U), and returns the same type of function, i.e. (T->U). Using this approach, your function can take functions such as result from itself as an argument.
The short version is that the Y combinator computes the fixed point of
a functional -- a function that consumes (and in this case, produces)
another function.
The trick is to define recursive functions as the fixed points of
non-recursive functions, and then to write a fixed-point finder -- the
Y combinator -- without using recursion.
From http://matt.might.net/articles/js-church/.
Now, since you return a function, your return will be "nested" in two steps; the outer defining the return of the closure, and the inner the return of the type. The key is the inner, recursive, return; where you call the input (parameter) function itself without explicitly using its name: you make use of the function parameter which is---as described above---constructed as a closure type that can hold the functions itself.
func myCombinator<T,U>(f: (T->U) -> (T->U)) -> (T->U) {
return {
(x: T) -> U in
return f(myCombinator(f))(x)
}
}
Using this function, you can, e.g., calculate factorial of a number without the functions explicitly referring to their own name
func factorialHelper(recursion: Int -> Int)(n: Int) -> Int {
switch n {
case 0: return 1
default: return n * recursion(n-1)
}
}
let factorial = myCombinator(factorialHelper)
print("\(factorial(4))") // 24
For reference on the Y combinator and recursive closures in the context of Swift, see e.g.
https://xiliangchen.wordpress.com/2014/08/04/recursive-closure-and-y-combinator-in-swift/
https://gist.github.com/kongtomorrow/e95bea13162ca0e29d4b
http://rosettacode.org/wiki/Y_combinator#Swift
It's the second reference above from which the example in this answer is taken.
Returning shortly to the U combinator, there is one simple "native" swift case (however, quite useless) that at least simulates the form lambda f: f(f).
Consider a void function, say f, taking an empty tuple type as single function parameter. The empty tuple () is a type (typealias Void refers to type ()) as well as the single value of that type. Since f is void (no explicit return) it implicitly returns an empty tuple () as a value.
Hence---although not really related to the U combinator---you could write something like
func f(_: ()) { }
var lambda_f = f(f())
lambda_f = f(f(f()))

Are there any possible explicit uses of instances (values) of empty tuples (), i.e., of instances of typealias 'Void'?

Question:
Are there any possible explicit uses for the empty tuple (), as a value (and not as a type) in Swift 2.x?
I know that these empty tuples can be used in the standard sense to define void functions. When I mistakenly defined a variable with a empty tuple value var a = () (of type ()), I started wondering if these empty tuple values can be used in some context. Does anyone know of such an application?
Example: possible application with array and optionals?
As an example, we can create an optional array of empty tuples that, naturally, can only hold either nil or ():
/* Optionals */
var foo: ()? = ()
print(foo.dynamicType) // Optional<()>
var arr : [()?] = [foo]
for i in 2...8 {
if i%2 == 0 {
arr.append(nil)
}
else {
arr.append(foo)
}
}
print(arr) // [Optional(()), nil, Optional(()), ... ]
With the small memory footprint of empty tuple, this could seem neat for micro-memory-management for a "boolean nil/not nil", but since type Bool have the same small footprint, I can't really see any direct use here, even in the (unlike) scenario that we really need to go bit-low optimization on our operations.
Perhaps I'm just chasing my own tail with some narrow unusable applications, but anyway: are there any possible explicit uses for these void () beings (as instances, not types)?
There are lots of places that () can be useful when playing around with "CS" problems, which often have the form "implement X using Y even though you really already have X." So for instance, I might say, implement Set using Dictionary. Well, a Dictionary is a Key/Value pair. What should the type of the Value be? I've actually seen this done in languages that have Dictionaries but not Sets, and people often use 1 or true as the value. But that's not really what you mean. That opens up ambiguity. What if the value is false? Is it in the set or not? The right way to implement Set in terms of Dictionary is as [Key: ()], and then you wind up with lines of code like:
set[key] = ()
There are other, equivalent versions, like your Optional<()>. I could also implement integers as [()] or Set<()>. It's a bit silly, but I've done things like that to explore number theory before.
That said, these are all almost intentionally impractical solutions. How about a practical one? Those usually show up when in generic programming. For example, imagine a function with this kind of form:
func doThingAndReturn<T>(retval: T, f: () -> Void) -> T {
f()
return retval
}
This isn't as silly as it sounds. Something along these lines could easily show up in a Command pattern. But what if there's no retval; I don't care about the return? Well, that's fine, just pass a () value.
func doThing(f: () -> Void) {
doThingAndReturn((), f: f)
}
Similarly, you might want a function like zipMap:
func zipMap<T, U>(funcs: [(T) -> U], vals: [T]) -> [U] {
return zip(funcs, vals).map { $0($1) }
}
This applies a series of functions that take T to values of type T. We could use that even if T happens to (), but we'd have to generate a bunch of () values to make that work. For example:
func gen<T>(funcs: [() -> T]) -> [T] {
return zipMap(funcs, vals: Array(count: funcs.count, repeatedValue: ()))
}
I wouldn't expect this to come up very often in Swift because Swift is mostly an imperative language and hides its Void in almost all cases. But you really do see things like this show up in functional languages like Scala when they bridge over into imperative programming.
Suppose you have two functions overloading the same name:
func foo()
func foo() -> Int
The first doesn't return anything, the second returns some kind of value. Attempting to call either of these will in most cases get you a compiler error about ambiguity.
foo()
let a = foo()
You'd think that the compiler would know that the first call unambiguously refers to the first function, because it assumes no return value. But in actuality, the return type of a function with no declared return type is Void, or (). So the first call is actually more like this:
let _ = foo()
And absent a type annotation for the discarded lvalue, the compiler can't infer which foo to call. You can use explicit type annotations to disambiguate:
let b: Void = foo()
let c: Int = foo()
Okay, it's not a very great or common use case for Void, because it's a situation you'd tend to avoid getting into in the first place. But you asked for a use... and it is a use of () as a value and not just a type, because you can retrieve it from b after assignment (for all the good that does you).
Just beware, when you look deeply into the Void, the Void also looks into you. Or something like that.

When to use the generic parameter clause

I'm new to generics in swift, and while reading some books, I came across something I don't understand. In generic functions, when is it appropriate to use the type parameter (the right after the function name)? and when is it inappropriate?
Here an example where it is not used (signature only; from standard library):
func sorted(isOrderedBefore: (T, T) -> Bool) -> Array<T>
Here's an example of where it is used (taken from a book I'm reading):
func emphasize<T>(inout array:[T], modification:(T) -> T) {
for i in 0 ..< array.count {
array[i] = modification(array[i])
}
}
I read Apple's swift language reference, section: Generic Parameters and Arguments. But it is still not clear to me. Thanks in advance for any insight.
 
In the first example, the generic parameter is coming from the type it is defined within. I believe it is declared within Array which already has the generic type T.
In the second example, the function itself is declaring the generic parameter. If I am not mistaken, this function is a global function. It is not already within a scope that defines a generic T.
It is only inappropriate to declare a new generic parameter in a function that obscures or tries to replace the one already declared in it's scope. For example, when extending an array, this would be inappropriate:
extension Array {
func myFunc<T>() {
}
}
Here we are defining a new T that is obscuring the original T that is already declared in the declaration of Array.
In all other circumstances where you want a generic type, you should be declaring it yourself.