Swift's functional programming detailed _swift

Source: Internet
Author: User
Tags array length arrays closure data structures function definition in python


One of the most important advantages of Swift compared to the original objective-c is that it provides better support for functional programming. Swift offers more syntax and some new features to enhance functional programming, and this article discusses some of these.



Swift Overview



Programmers with some experience in programming languages, especially those who have experience with many different types of programming languages, are more adept at learning new languages. The reason is that the programming language itself also has a variety of paradigms, grasp these characteristics can be easier to get started.



In the beginning of a new language, the general attention to the content are:



1. Native data structure
2. Operator
3. Branch control
4. What is the object-oriented implementation of an object-oriented programming language?
5. If it is a functional programming language, what is the implementation of the function-oriented programming?



By reading the first chapter of the Swift document, you can have a general impression of the language. For example, for data structures, Swift is roughly the same as other programming languages, with Int, Float, Array, Dictionary, and so on, and the operators are basically the same as the C language. This article focuses on a few counts of the features of swift functional programming, so let's assume that you have some understanding of Swift's basic syntax.



For a programming paradigm, there are some important points to grasp. For languages that support functional programming, the general characteristics may include the following:



1. Support recursion
2. The function itself is the constituent element of the language's top Class and supports higher-order functions and closures
3. function calls without possible side effects (Side Effect) conditions



Next, we'll take stock of the content individually.



Recursion



Swift supports recursion, and in fact it is hard to find a recursive programming language now. There is no difference between writing a recursive call in Swift and other programming languages:





Copy Code code as follows:

Func fib (n:int)-> Int {
If n <= 1 {
Return 1
}
else {
return fib (n-1) + fib (n-2)
}
}
FIB (6)//Output 13





There is nothing to say about Swift's recursion. As a common sense, we know that recursion needs to consume stack space. In functional programming languages, recursion is a very common method, but careless use can easily lead to stack overflow problems. If you rewrite your code as a non-recursive implementation, which may cause your code to become less readable, one trick is to use "tail recursion" and have the compiler optimize the code.



An example of a Common Lisp's tail recursion is





Copy Code code as follows:

(Defun fib (n)
(fib-iter 1 0 N))
(Defun fib-iter (a B count)
(if (= Count 0)
B
(Fib-iter (+ a B) A (-Count 1)))





We can also rewrite our Swift code in the same form.





Copy Code code as follows:

Func Fibiter (A:int, B:int, count:int)-> Int {
If count==0 {
Return b
}
else {
Return Fibiter (A + B, a, count-1)
}
}
Func fib (n:int)-> Int {
Return Fibiter (1, 1, N);
}





We can playground to see if the iterative results of tail recursion are changed.






It is noteworthy that there is a question of Swift. Although Swift supports nested functions, the exc_bad_access error occurs when we include fibiter as a higher order function within the FIB function, and it is not clear whether this is a language limit or a Bug.



Swift's higher-order functions and closures



In the Objective-c era, using block to implement higher-order functions or closures is already a very mature technique. The improvement of Swift compared to objective-c is that it adds a lot of grammatical convenience to functional programming.



The first is the support of higher-order functions, which can be defined in functions, and here is a very concise example.





Copy Code code as follows:

Func greetinggenerator (object:string)-> (greeting:string)-> String {
Func saygreeting (greeting:string)-> String {
Return greeting + "," + Object
}
Return saygreeting
}
Let Saytoworld = Greetinggenerator ("World")
Saytoworld (greeting: "Hello")//"Hello, World"
Saytoworld (greeting: "Hello")//"Hello, World"





If you use block to achieve these functions, readability will not be so good. and block's syntax itself is also more bizarre, before the person is not less spit slot. Swift is more convenient from this point of view. In fact, you can assign functions as objects in Swift, which is the same as many functional programming languages.



As a hodgepodge, Swift's function system is also a shadow of JavaScript. For example, you can define a function as follows:





 code as follows:

Let add = {
(A:int, B:int)-> Int in
Return a+b
}
Add (1, 2)//3





After the equals sign is given the variable add is a closure expression, so it is more accurate to say that a closure is assigned to a constant. Note that in a closure expression, the In keyword is preceded by the form definition of the closure, followed by the concrete code implementation. The closures in Swift are no different from anonymous functions. If you assign it to an object, it is the same as the same practice in JavaScript. Fortunately Swift as a C-series language, its spoke if, and so on, itself is scoped, so the following JavaScript pits do not appear:





code as follows:

if (somenum>0) {
function A () {alert ("one")};
}
else {
function A () {alert ("two")};
}
A ()//would always alert "two" in most of browsers





Swift's closure expressions and functions can be used as parameters for functions, and we can see the consistency of closures and functions from the following code:


code as follows:

Func function () {
println ("This is a function")
}
Let closure = {
()-> () in
println ("This is a closure")
}
Func Run (somethingcanrun: ()-> ()) {
Somethingcanrun ()
}
Run (function)
Run (closure)





A closure similar to Ruby,swift as a function parameter makes a bit of syntactic sugar. When using block in Ruby, we can write this:





 code as follows:

(1...5). Map {|x| x*2}//=> [2, 4, 6, 8]





We can get almost the same expression in Swift.





 code as follows:

var a = Array (1..5). map {x in x*2}
A = [2, 4, 6, 8]





That is, if the last parameter of a function is a closure, it can be syntactically placed outside the function call. Closures can also be used to represent the No. 0, 1th parameters, and so on, in $ $. Basic operators can also be considered as functions. The following are several ways to implement reverse inverted functionality.





 code as follows:

Let Thingstosort = Array (1..5)
Var reversed1 = sort (Thingstosort)  { a, b in a<b} var reversed2  = " sort (thingstosort)  { $0 < $1}" var reversed3 = " sort ( thingstosort, <)  // operator as a function " all the above  are [5, 4, 3, 2, 1]<= "pre=" ><p> overall, Swift has gone a long way in adding convenient function operations and adding related grammatical sugars, It basically integrates the features that are more convenient in various languages at present. Practicality is good. </p><p><strong>side effects</strong></p><p> in Computer science, function side effects mean that when a function is called, in addition to returning a function value, Also has an additional effect on the main invocation function. For example, modify a global variable (a variable outside a function) or modify a parameter (<a href= "Http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29 target=" _ Blank ">wiki</a>). function side effects can cause unnecessary trouble to the program. </p><p> to reduce function side effects, many functional programming languages strive to achieve what is called a "pure function." A pure function is the only channel in which a function is exchanged with the outside world as a parameter and a return value, without being disturbed by the external variables of the function. At first glance this seems to contradict the concept of closure, because an important feature of the closure itself is the access to the context of the function definition. </p><p> in fact, in order to support pure functions in this case, some programming languages such as Clojure provide a data structure that is immutable (or Persist). So there is no "variable" in our traditional sense."The concept. In Python, for example, String Str is a kind of immutable data structure. You can't make changes to the original string, and each time you want to do something like that, you're actually generating a new str object. However, the list structure in Python is variable. And looking at the following code, modifying a string in Python does not affect B, but the same action on the list produces a different result: </p><pre class= "Brush:js;toolbar:false" >a  =  "hello, "
b = A
A = "World"
Print a # Hello, world
The Persist nature of the data structure of print B # hello,</pre><p>swift is somewhat similar to that of Python. Note that Swift has two concepts of variables and constants, variables using var declarations, constants using let declarations, and when using the Var declaration, the string in swift behaves like Python, so modifying a string can be interpreted as generating a new string and modifying the pointer. Similarly, arrays and dictionaries that use the Var declaration are also variable. </p><p> objects using let declarations in Swift cannot be assigned, and basic data results can become variable, but the situation is more complicated. </p><pre class= "Brush:js;toolbar:false" >let adict = ["K1": "V1"]
Let Anarray = [1, 2, 3, 4]
adict["K1"] = "newval"//!! would fail!!
Anarray.append (5)//!! would fail!!
Anarray[0] = 5 // anarray = [5, 2, 3, 4] now !</pre ><p> it can be seen from the above code that dictionaries using let declarations are completely immutable, but arrays can change the values of array elements, although they cannot change their length. Swift's documentation points out that this is actually an array of fixed-length arrays that facilitates compilation optimization for better access performance. </p><p> to sum up, the object is variable relationship is actually slightly complex, can be summed up as: </p><ol class= "List-paddingleft-2" ><li><p > Using var and let,int and string types are immutable, but Var can be assignable to a variable </p></li><li><p> use let-declared constants cannot be assignable < /p></li><li><p> using let-declaration dictionary is completely immutable </p></li><li><p> The array length with let declarations is immutable, but you can modify the value of an element </p></li><li><p> class objects that use let declarations are mutable </p></li></ Ol><p> to sum up, even if the use of let declaration of the object may be variable, so in the case of multithreading can not achieve "no side effects" requirements. </p><p> In addition, Swift's function does not have pointers, but it still modifies variables by parameters. Just add the InOut keyword to the function's parameter definition. This feature is very C-style. </p><p> personally feel that in support of a tuple to achieve multiple return values, this feature is not only a chicken, but also a result of the program to produce "side effects" characteristics. Swift supports this feature, perhaps more for compatibility with objective-c and for the convenience of building bridges between two languages. </p><pre class= "Brush:js;toolbar:false" &GT;func inc (Inout a:int)  {
A + + 1
}
var num = 1
Inc (&AMP;NUM)//num = 2 now!</pre><p> in summary, using Swift's own data structures does not do a good job of "no side effects" of "pure functional" programming, and it is no better than Python, Ruby This kind of language goes farther. Fortunately, as a highly focused language, developers have implemented a set of data structures and libraries that fully meet the immutable requirements: SWIFTZ. By insisting on using the data structures provided by let and SWIFTZ, we can achieve "pure functional" programming. </p><p><strong> Summary </strong></p><p> In my opinion, Swift has achieved a lot of bright spots in other languages, but the overall implementation is not very neat. It adds a lot of features to functional programming, but can only achieve an average level of control over side effects. Some of the features look like they were meant to be compatible with the original objective-c. </p><p>swift is more convenient to write than Objective-c, and it should be possible to write from an IDE like Xcode. It is a disadvantage that Swift supports only a small number of native data structures without a standard library and no cross-platform features at this time. After a careful reading of the document, Swift itself is found to have a lot of grammatical details, such as the use of switch-placement statements. The easy way to get started is not as good as it used to be. I personally do not think that this language will be very attractive to the developers of other platforms. </p><p>swift is a very powerful language, and after its stable release I think I will switch from OBJECTIVE-C to Swift for programming, which is likely to become the first choice for IOS and MAC development in the future. </p>
</b}>




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.