[Swift] Day07: kerihua and swiftday07 kerihua
Curialization in Swift
I am very grateful to you for your learning notes.
Previous episode: Theoretical preparation
Three interesting concepts have been introduced during the course of KE Lihua. I would like to share with you here.
Partial Function)
A partial function is a function that defines only a subset of a function's definition field. It is a mathematical concept.
Partial functions are defined as follows:
The function f (recorded as f: X → Y) from the input value set X to the possible output value set Y is the relationship between X and Y, if f can map multiple inputs to one output, but one input cannot map to multiple outputs, it is a partial function.
In other words, the definition domainXSome values may exist in the value range.YNo corresponding value. From the definition, partial functions are supersets of functions. That is to say, all functions are partial functions, but not all partial functions.
Partial Function Application (Partial Application | Partial Function Application)
The concept above is a concept in mathematics and has nothing to do with what we will be in touch. The main link with us is the Partial function Application ).
Partial function applications are defined as follows:
In computer science, partial function applications refer to the process of generating new functions by fixing some parameters of the original functions. The number of parameters of new functions is less than that of the original functions.
The mathematical formula is used for demonstration, such as the original function.fThere are three parameters:f:(X×Y×Z)→NBy binding the first parameterX, We can get a new function:partial(f):(Y×Z)→N.
Partial functions in programming, such as the ones mentioned by Liao Xuefeng in partial functionsfunctoolsThe module usage is actually a partial function application, also known as a local function application. The youdao dictionary is translated into a single knife and is not mentioned in this table.
To avoid obfuscation, all the Partial functions mentioned in this article are Partial function applications in programming ).
Partial functions are similar to setting default values for function parameters, but partial functions are more flexible. For example, in the following c-language code,foo23The function isfooFunction bias function, parameterbIs bound23:
int foo(int a, int b, int c) { return a + b + c;}int foo23(int a, int c) { return foo(a, 23, c);}Kerihua
There are some relationships between kerialization and partial functions, but they are two completely different concepts.
Colialization is defined as follows:
Currying is a function that converts a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function, and return the technology of the new function that accepts the remaining parameters and returns results.
The original function is a common function:f:(X×Y) → ZThe function becomes:curry(f):X → (Y→Z).
We use a few pieces of js Code to demonstrate the Keri process. First, let's look at a common function.foo, Returns the square of the parameter:
var foo = function(a) { return a * a;}
Assume that all our functions can have only one parameter, you can simulate a multi-parameter function in the following way:
var foo = function(a) { return function(b) { return a * a + b * b; }}
We can callfoo(3)(4).
Keri solves the problem of converting multi-parameter functions into chained calls of a series of single-parameter functions.
The basic idea behind keri Is that a function can be applied locally, meaning that some parameter values can be specified before a function is called and a new function is returned. That is, the basic idea of partial functions.
Summary
As you can see, corialize performs the function ~~ Dismember ~~ Split, so that we can easily implement partial functions. For example:
var foo = function(a) { return function(b) { return a * a + b * b; }}var foo3 = foo(3);foo3(4);
This is coming out. Functionfoo3YesfooFunction.
Here is a brief summary of the relationship between partial functions, colitization, and the two:
- Partial function application: Fix several parameter values of the original function to obtain a new function.
- Function kerialization: a method that uses anonymous Single-parameter functions to implement multi-parameter functions.
- Relationship: kerihua can easily implement some partial function applications.
Centralized: colialization and partial functions
I 've mentioned a lot of things before. Next let's look at KE Lihua in Swift.
Program preview: the example below is very simple, so you can see it. We hope to use these simple examples to demonstrate the most critical part of colitization.
Traditional means: Honestly passing Parameters
Let's first write the simplest thing: the counter. After each operation, + 1 is required:
func add(a:Int) -> Int{ return a + 1;}var a = 0a = add(a) // 1a = add(a) // 2
But every time I add 1 more, the step is a little small. Sometimes we may also need + 2, + 3, + 4, which is so simple that we can put the step we need to add in the parameter:
func add(a:Int, b:Int) -> Int{ return a + b ;}var a = 0a = add(a, 1) // 1a = add(a, 2) // 3
It seems that there is no problem. So the problem arises: I only need to add 1 for most of the time. I may only need 90 secondary + 1 for 100 calls. For the remaining 10 calls, multiple parameters are required for each line of code, is it troublesome? We can solve this problem by setting the default value.
Advanced method: You can set the default value.
When defining a function, we can set the default value to 1:
func add(a:Int, b:Int=1) -> Int{ return a + b ;}var a = 0a = add(a) // 1a = add(a, b:2) // 3
If you want to + 1, line, you don't need to write the parameter I have set for you to auto + 1; if you want to + 2 + 3, line, love to add a few plus a few, write it to parameters.
It seems that there is no problem. So the question is: I have half of the time plus 1, half of the time plus 2, and some time plus 3 + 4. How can I play?
Alas, it's really a tough little goblin.
Ke Xue's means: achieved through KE Lihua
Unlike the previous example, the colized function returns a new function instead of the computed result. The calculated result is obtained through the returned new function calculation:
func add(b:Int)(a:Int) -> Int{ return a + b ;}let addOne = add(1)let addTwo = add(2)var a = 0a = addOne(a: a) // 1a = addTwo(a: a) // 3
In this example, we generate two new functions:addOneAndaddTwoPerform the + 1 and + 2 Operations respectively. As you can see, it is very convenient to implement partial functions through colialization, and everything goes with its nature.
Through this example, we can see that kerihua is the method of partial function, and partial function is the ~~ behind kerihua ~~ Man ~~ Thoughts.
Next set: instance method and Keri
In fact, the instance method in Swift is also the Keri method. You can pass an instance as the first parameter.
We can also take the counter as an example:
class Counter { var b: Int = 1 func add(a:Int) -> Int{ return a + b ; }}
We can initialize the instance object and then call:
let counter = Counter()var a = counter.add(1) // 2
We can also do this:
let add = Counter.add // Functionlet counter = Counter()var a = add(counter)(1) // 2
These two are completely equivalent.
It's amazing, isn't it? Note,let add = Counter.addThis definition is not followed by parentheses. That is to say, we didn't call it, but pointed to it, and pointed to it like a pointer.
We can hold downoptionKey to viewaddType:let add: Counter -> (Int) -> Int. Its parameter isCounterType instance, and another new function is returned. The parameter type of this new function isInt, The returned type is alsoInt, Which is the same as the function type defined in the class.
It seems interesting, but the question is: What is the purpose?
I still cannot answer this question, because I just got in touch with this part of content. I can only be a knowledge Porter.
In the article "Instance Methods are Curried Functions in Swift", the author provides an example: implementControl:
protocol TargetAction { func performAction()}struct TargetActionWrapper<T: AnyObject> : TargetAction { weak var target: T? let action: (T) -> () -> () func performAction() -> () { if let t = target { action(t)() } }}enum ControlEvent { case TouchUpInside case ValueChanged // ...}class Control { var actions = [ControlEvent: TargetAction]() func setTarget<T: AnyObject>(target: T, action: (T) -> () -> (), controlEvent: ControlEvent) { actions[controlEvent] = TargetActionWrapper(target: target, action: action) } func removeTargetForControlEvent(controlEvent: ControlEvent) { actions[controlEvent] = nil } func performActionForControlEvent(controlEvent: ControlEvent) { actions[controlEvent]?.performAction() }}
Usage and peacetime:
class MyViewController { let button = Control() func viewDidLoad() { button.setTarget(self, action: MyViewController.onButtonTap, controlEvent: .TouchUpInside) } func onButtonTap() { println("Button was tapped") }Next set: Other
Because it has not been used in practice, Ke Lihua has not made too many comments for the moment. Based on our current understanding, it makes it easy for us to call functions locally, making the code more flexible and clearer.
If you want to feel the original sense of kerihua, you may wish to contact Haskell. In Haskell, multiple parameter functions are implemented through colialization. It is written by Haskell Brooks Curry, and is the name of Curring (but not invented by him ).
If you are using Mac, you can download Haskell Platform for Mac and then useghciCommand to try the Haskell code.
Of course, there are also anti-kerialization. If you are interested, you can continue to understand it :)
References
- Wikipedia-Currying
- Wikipedia-Partial Application
- What is the advantage of currying?
- Currying and Partial Function)
- Why Curry Helps
- Function Scala
- Curried Functions in Swift
- Swift Function Currying
- Instance Methods are Curried Functions in Swift
- Partial Function in Python
- Function _ (mathematics)
- Programming Challenge: Are You a Swift Ninja? Part 2
- Currying and Partial Application