How to understand the currying in Swift? - swift

I'm new to Swift, and when I look the book, I found the currying in Swift is complicated, and I write the code follow the book, such as:
func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { x in { y in f(x, y) } }
}
func paraFunc(pa: Int, pb: Int) -> Int {
return pa - pb
}
var cab = curry(paraFunc)
cab(2)(3)
and I don't know how to comprehend the "-> A -> B -> C". And I know the Generics. But I confused about the func curry, how it works? and anybody can help me?

-> operator is right associative. So we can rewrite curry function like this.
func curry<A, B, C>(f: #escaping (A, B) -> C) -> ((A) -> ((B) -> C)) {
return { x in { y in f(x, y) } }
}
Every ( matches with { inside return part.
EDIT: Further explanation
curry function takes a non-curried two argument function and makes it curried. For example we have:
func sum(a: Int, b: Int) -> Int {
return a + b
}
Now we can use this function like this:
let result = sum(3, 6)
But if we make it curried
let curriedSum = curry(sum)
Now we can use it like this:
let result = curriedSum(3)(6)
At first this seems unnecessary and complex. But think about what next expression does.
let sumWith3 = curriedSum(3)
This produces a new function that takes an Int sums it with 3. Now here we created a new function from another function. Now we can use it like any other function.
Currying is common paradigm in functional programming. In fact in Haskell (another functional programming language) every function is curried by default.

Related

Figuring out memoize from WWDC 2014 - Session 404

I'm working through understanding the parameters used in the (simple) version of the memoized fibonacci explained in the Advanced Swift session (jump to 00:38:00)
In the session the following memoize function is defined (adapted to Swift 3)
func memoize<T: Hashable, U>(body: #escaping (T) -> U) -> (T) -> U {
var memo = Dictionary<T, U>()
return { x in
if let q = memo[x] { return q }
let r = body(x)
memo[x] = r
return r
}
}
And it will wrap simple functions, for example:
let ntos = memoize {(n: Int) -> String in
print("Must evaluate something")
return "\(n)"
}
print(ntos(3))
print(ntos(3))
print(ntos(30))
output:
Must evaluate something
3
3
Must evaluate something
30
The type of ntos is (Int) -> String so the T in memoize becomes Int and U becomes String.
But for the fibonacci function, the example apple are using is
let fibonacci = memoize {
fibonacci, n in
n < 2 ? Double(n) : fibonacci(n: n - 1) + fibonacci(n: n - 2)
}
Here I'm not sure what types T, and U are adapting? and how the function behaves for the recursive nature? How the closure parameter declaration fibonacci, n translate to the type memoize (T) -> U body parameter?
Why fibonacci is even in the definition of closure passed to memoize? I assume it's something to do with the idea of curried functions (that was replaced by closures in Swift 3) but the implementation syntax just doesn't clicks for me.
I've decided to it a step further and wrote a full fledges walk through of memoize

Is it possible to call a function as a parameter of another function in Swift?

Is it possible to call a function as a parameter of another function in Swift??
I am making a sound effects app in Swift which uses different effects like AVAudioUnitReverb() and AVAudioUnitDistortion() etc. I wanted to create a single function and just be able to call which effects I wanted to do.
Because in Swift functions are first-class types, you can pass it as an argument to another function.
Example:
func testA() {
print("Test A")
}
func testB(function: () -> Void) {
function()
}
testB(testA)
You can pass in functions as parameter my typing the parameter with the same signature.
As sunshine's example just deals with Void parameters and return types, I want to add another example
func plus(x:Int, y:Int) -> Int {
return x + y
}
func minus(x:Int, y:Int) -> Int {
return x - y
}
func performOperation (x:Int, _ y:Int, op:(x:Int,y: Int) -> Int) -> Int {
return op(x: x, y: y)
}
let resultplus = performOperation(1, 2, op: plus) // -> 3
let resultminus = performOperation(1, 2, op: minus) // -> -1
note: Of course you should consider dynamic typed parameters. For simplicity here just Ints
this is called Higher Order Functions and in many languages this is the way of doing it. But often you don't won't to explicitly create functionss for it. Here Closures are a perfect tool:
The function performOperation stays untouched, but the operations are implemented differently:
let plus = { (x:Int, y:Int) -> Int in
return x + y
}
let minus = { (x:Int, y:Int) -> Int in
return x - y
}
let resultplus = performOperation(1, 2, op: plus)
let resultminus = performOperation(1, 2, op: minus)
Often this would be preferred as it doesn't need methods to be added to a class, pretty much like anonymous functions in other languages.
More on this and how it is used in the swift standard library: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/
I would recommend book "IOS 9 Programming Fundamentals with Swift" by Matt Neuburg, especially subchapter "Functions".
You should not only find the answer for your question:
func imageOfSize(size:CGSize, _ whatToDraw:() -> ()) -> UIImage {
...
}
But also how to construct function that returns the function:
func makeRoundedRectangleMaker(sz:CGSize) -> () -> UIImage {
...
}
As well as brief introduction to Curried Functions.

Curried infix operators in swift. Is it possible?

I am trying to implement function composition. At first I defined a function that is named compose.
func compose<A,B,C>(f:(B -> C))(g: (A -> B)) -> A -> C {
return { f(g($0)) }
}
This works great. For example if I have not and isEven functions like
func not(value: Bool) -> Bool {
return !value
}
func even(value: Int) -> Bool {
return value % 2 == 0
}
The odd function can be defined in terms of not and even like this:
func odd(value: Int) -> Bool {
return compose(not)(isEven)(value)
}
Then I decided to use a custom operator instead of compose function. The custom operator is ... At first I just copied compose function and changed it name to ... Here is how it looks like:
infix operator .. { associativity left }
func ..<A,B,C>(f:(B -> C))(g: (A -> B)) -> A -> C {
return { f(g($0)) }
}
Here Xcode gives the error: "Unary operator implementation must have a 'prefix' or 'postfix' modifier"
After that I changed the operator to this:
infix operator .. { associativity left }
func ..<A,B,C>(f: (B -> C), g: (A -> B)) -> A -> C {
return { f(g($0)) }
}
And odd function to this:
func odd(value: Int) -> Bool {
return (not..even)(value)
}
Or as a closure:
let odd = not..even
And this code worked. Now I know maybe there is no benefit here to make .. operator curried here but I wonder why curried operators is not allowed? For example if + operator were defined as curried function we would make something like this:
let array = [1,2,3,4]
array.map((+1))
You're asking for something known as operator sections, or the ability to partially apply binary operators on the left or the right. Unfortunately, Swift allows only fully uncurried operators, which means you have to get a little creative. If we regard an operator as a binary function op : (A, A) -> A, then its curried form, curry-op : A -> A -> A, is simply a unary function returning a unary function. We can fake this with custom prefix and postfix operators that simulate right and left sectioning respectively.
Here's prefix and postfix +
prefix func +<A : protocol<IntegerLiteralConvertible, IntegerArithmeticType>>(r : A) -> (A -> A) {
return { l in l + r }
}
postfix func +<A : protocol<IntegerLiteralConvertible, IntegerArithmeticType>>(l : A) -> (A -> A) {
return { r in l + r }
}
This allows you to write code such as
let l = [Int](1...10) /// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l.map(+5) /// [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
instead of the old
l.map({ x in x + 5 })
Let's write some (incomplete) definitions for the terms in your question:
non-curried two-argument function: A function that takes two arguments and returns some value. Example: func add(a: Int, b: Int) -> Int
curried two-argument function: A function that takes one argument and returns another function that takes one argument and returns some value. Example: func add(a: Int)(b: Int) -> Int
infix (binary) operator: An operator that takes two operands, an lhs and an rhs argument, and returns some value. Example: func +(lhs: Int, rhs: Int) -> Int
prefix/postfix (unary) operator: An operator that takes a single operand, either after or before the operator, and returns some value. Example: func -(x: Int) -> Int
Curried functions are more akin to unary operators than binary ones; that's why Swift is complaining.

Why do curried functions require external parameter names?

Given this simple currying function:
func foo(x:Int)(y:Int)->String{
return "\(x) with \(y)"
}
I'd expect to be able to do something like this:
let bar = foo(1)
bar(2) //<- error: Missing argument label 'y:' in call
If I label the call to bar (as in bar(y:2)) everything works fine. But I don't understand why the parameter name is necessary. Is there any way to avoid it?
The obvious thing:
func foo(x:Int)(_ y:Int)->String ...
does not seem to work.
It's a bug, you should file a radar at bugreport.apple.com
As a confirmation, if you place an underscore, like this
func foo(x: Int)(_ y: Int) -> String
you get a warning
Extraneous '_' in parameter: 'y' has no keyword argument name
So it explicitly says that y has no external name, but it still requires one when called, which is clearly against the language specification.
I believe it is a compiler bug, your example should work as described in The Swift Programming Language book where they mention declaring curried functions:
func addTwoNumbers(a: Int)(b: Int) -> Int {
return a + b
}
addTwoNumbers(4)(5) // Returns 9
https://bugreport.apple.com
good find!
I am not sure I fully understand your currying. Here is my take on it. I have a function foo as follows:
func foo(x:Int, y:Int) -> String{
return "\(x) with \(y)"
}
let bar = foo(1, 2) // gives "1 with 2"
I wish to curry this function to 'fix' the value for x, so do so as follows:
func fooCurry(x:Int) -> (Int -> String) {
func curry(y:Int) -> String {
return foo(x, y)
}
return curry
}
The above returns a new function which can be used as follows:
let curriedFoo = fooCurry(1)
let barWithCurry = curriedFoo(2) // gives "1 with 2"
The function returned by fooCurry has the signature (Int -> String), which means that the parameter does not have an external name.
Not the best syntax, but if you want to get around it for now, you can use the following for basic curried functions:
func foo(x:Int) -> Int -> String {
return {
return "\(x) with \($0)"
}
}
Then you can just do:
let bar = foo(1)
bar(2) //-> 1 with 2
Now obviously the problem with this becomes obvious when you want to write a curried function for piping four Ints for example:
func makerAdders(a:Int)(b:Int)(c:Int)(d:Int) {...}
becomes like this:
func add(a:Int) -> Int -> Int -> Int -> Int {
return {
b in return {
c in return {
d in return a + b + c + d
}
}
}
}
The inner closures make it a bit better than using inner functions, but again it defeats the purpose of the nice func add(a:Int)(b:Int)(c:Int)(d:Int) {return a+b+c+d} syntax.
Definitely a bug in the compiler as far as I can tell. Until it's fixed you can get a properly curried version of any function using these functions (note that I've included cases for two and three arguments, extend at your leisure:
func curry<A,B,C>(f: (A, B) -> C) -> A -> B -> C {
return { a in { b in return f(a,b) } }
}
func curry<A,B,C,D>(f: (A, B, C) -> D) -> A -> B -> C -> D {
return { a in { b in { c in return f(a,b,c) } } }
}
Just use:
curry(addTwoNumbers)(1)(2)

Curry Function in Swift

I want to make a function that return a curry function like below
func addTwoNumbers(a: Int)(b: Int) -> Int {
return a + b
}
addTwoNumbers(4)(b: 6) // Result: 10
var add4 = addTwoNumbers(4)
add4(b: 10) // returns 14
What is the return type of such function and how can I generate a function like this using a function that take Variadic parameters.
func generateCurry(.../*Variadic parameters*/) -> .../*curry function type*/ {
return ...//curry function
}
I want a generic solution and not take only Int as arguments in the parmeter of the generateCurry function
let curried = curry(func(a, b, c) {
print(a + b + c)
})
curried(1)(2)(3) //prints 6
You can achieve this pretty easily with closures:
/// Takes a binary function and returns a curried version
func curry<A,B,C>(f: (A, B) -> C) -> A -> B -> C {
return { a in { b in f(a, b) } }
}
curry(+)(5)(6) // => 11
let add: Int -> Int -> Int = curry(+)
add(5)(6) // => 11
It would be really nice to be able to do the same thing for functions that take 3, 4 or more arguments, but without duplicating the implementation. The signature of such a function might start something like:
/// Take a function accepting N arguments and return a curried version
func curry<T>(args: T...) -> /* ? */
What would the return type be? It would change based on the input to the function. This definitely isn't possible in Swift at the moment, and I don't think it would be possible at all without some kind of macro system. But even with macros I don't think the compiler would be satisfied unless it knew the length of the list at compile-time.
Having said that, it's really straight-forward to manually overload the currying function with a version that accepts 3, 4, 5 or more parameters:
func curry<A,B,C,D>(f: (A, B, C) -> D) -> A -> B -> C -> D {
return { a in { b in { c in f(a,b,c) } } }
}
func curry<A,B,C,D,E>(f: (A, B, C, D) -> E) -> A -> B -> C -> D -> E {
return { a in { b in { c in { d in f(a,b,c,d) } } } }
}
// etc.
I'm not sure this is actually going to be possible in the same way it is inside of languages like Python.
The core problem I see to having a single generic solution is the strong typing of the closures/funcs you want to accept.
You could fairly easily create a curry function that worked on a specific or common function signature, but as far as a general purpose curry I don't see a way for it to work. The issue is more than about the types of the arguments (as mentioned in comments) but also with the number of them.
I've written up a simple example of how you could implement a curry function. It works, but I don't see a sane way to have a truly generic one like you can in more loosely typed languages.
func add(a1: Int, a2: Int) -> Int {
return a1 + a2
}
func curry(argument: Int, block: (Int, Int) -> Int) -> Int -> Int{
func curried(arg: Int) -> Int {
return block(argument, arg)
}
return curried
}
curry(5, add)(6)
In case you want to quickly get the curry function for any number of parameters, it's possible to generate it as shown in this gist.
The code is in Swift 2.2 and generates code for Swift 2.2 (at the moment). It uses simple template-based approach (a possible alternative is constructing an AST followed by code-generation):
func genCurry(n: Int, indent: Indent = .fourSpaces, accessLevel: AccessLevel = .Default, verbose: Bool = false) -> String {
// ...
// The bulky park is skipped for clarity.
return accessLevel.asPrefix + "func curry<\(genericParams)>(f: \(fSig)) -> \(curriedSig(n)) {\n"
+ indent.single + "return \(closure)\n"
+ "}\n"
}
I recently found that currying was removed back in Swift3. I created my own version which is repetitive but does the job.
precedencegroup CurryPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator <<== :CurryPrecedence
//1 param
func <<==<A,Z>(_ f: #escaping (A) -> (Z), _ p:A) -> () -> (Z) {
{ f(p) }
}
//2 param
func <<==<A,B,Z>(_ f: #escaping (A, B) -> (Z), _ p:B) -> (A) -> (Z) {
{ (A) in f(A,p) }
}
//3 param
func <<==<A,B,C,Z>(_ f: #escaping (A, B, C) -> (Z), _ p:C) -> (A, B) -> (Z) {
{ (A, B) in f(A,B,p) }
}
//4 param
func <<==<A,B,C,D,Z>(_ f: #escaping (A, B, C, D) -> (Z), _ p:D) -> (A, B, C) -> (Z) {
{ (A, B, C) in f(A,B,C,p) }
}
To use it:
let ten = (addTwoNumbers <<== 6 <<== 4)()
or
let ten = (addTwoNumbers <<== 6)(4)