Nonsense! Swift is not a multi-paradigm functional programming language

Source |  Cocoaphony 

Translator | Su Benru, Editor-in-Chief | Xi Yan

Cover Image | CSDN Download from Vision China

Exhibition | CSDN (ID: CSDNnews)

Since the advent of Swift, I have seen some strange comments that Swift is a functional programming language. I'm a little wonder why someone would say that, because Swift has few "functions". It is a very traditional object-oriented language that focuses on generic programming.

My guess is that people use a feature list to determine the paradigm of a language. But we use the term paradigm for a reason.

Paradigm-a worldview based on the theory and methodology of a specific scientific subject.

"A worldview." Yes, that's what it is.

The programming language paradigm is much like a music genre. They are messy things, we can argue where to draw lines, where to go, what is pure and what is fusion. But just like classical guitars and heavy metals belong to different genres, even if they both use guitars.

Some of my friends say they are very appreciative of music. They advertised themselves listening to "everything" music. From Jimmy Buffet's country rock to Metallica's heavy metal music, they like all the music played by these bands. The same is true for many programmers. They only know the paradigm of process programming and object-oriented programming. They believe that the difference between BASIC and Java is the difference between all languages. When they encounter a new language, their first question is "What is its grammar?" But I think their question should be "How does it view the problem?"

I have to say a lot about the programming paradigm. Like the music genre, there are many ideas and methods to classify music. My method is not the only way. But some methods are more useful than others. What I want to express is that Swift and Haskell are classified as a class of programming languages ​​because they both have maps, not as much as Wangga, Opera and Rock are classified as a class of programming languages ​​because they both have vocalists More useful.

Procedural (or imperative) programming is mainly concerned with breaking down problems into a series of actions. Its usual structure is "perform the first step, then repeat the second step until something is true, and then perform the third step." This paradigm is so common in popular programming languages ​​that many programmers Think this is the whole meaning of programming. Of course not. It is just a way to break down the problem. When faced with a problem, the question of procedural programming is: "What steps do I need to perform to solve this problem?"

Object-oriented programming (OOP) is primarily concerned with decomposing problems into self-contained objects with attributes, and a collection of methods to manipulate these attributes. Its usual structure is a hierarchy of classes with instances (objects) that inherit properties and methods. When faced with a problem, the problem with object-oriented programming is "What kind of objects are needed to work together to solve this problem?"

These two ways of thinking are extremely common in popular programming languages ​​and can work well together. Since the first machine languages ​​came out, procedural programming has been with us. Even the early automatic looms worked in a process paradigm.

Since the 1990s, object-oriented programming (OOP) has been the dominant programming. For a long time, it has been the mainstream paradigm, and has been dominating the CS program for a long time, so that many programmers believe that this is inevitable. They think that only "ancient languages" like Fortran will lack objects (and now, even Fortran supports objects).

But object-oriented programming (OOP) is just one way to think about problems. Functional programming is another way to think about problems. Functional programming mainly decomposes the problem into functions that accept and return immutable values. Its usual structure is a collection of functions that convert values ​​to other values, as well as various methods of combining functions. It avoids mutable states and does not require the evaluation of functions to be performed in any particular order. Functional programming treats a program as a mathematical problem, not a series of operations. When faced with a problem, the question of functional programming is "What kind of values ​​need to be converted in order to solve this problem?"

When you first started using Swift, what were you looking for first? Maybe how does it handle classes and protocols? Maybe how to call methods, declare and assign variables, and define attributes? Or is it the for and while loop versions? These are all tools for object-oriented programming and procedural programming. You think they are easy to obtain and easy to use, which is correct. You just need to know the grammar.

I heard someone describe Swift as "functional" , so when I opened my first Swift workspace, I immediately looked up the use of flatmap in Swift. I want to know how it is used to split a list into head and tail. I looked for a foldLeft equivalent and immutable collection. Swift seems to have no special treatment for them. This is not to say that a language must have these to be called a functional language, just as a language must have a for loop to be called a procedural language.

However, if I show you a new language and say that it is process-oriented and object-oriented, but you must use if and goto to implement the function of for loop, and there is no class inheritance, then you may Surprised by the choice of language features. A "functional" language that cannot simply divide a list into "first" and "not first" elements in O (1) time is a very strange functional language.

Swift has unique reduce and map functions. It also has first-class functions and pattern matching. And, it also has some features that are also common in other functional languages. Its syntax even feels very similar to Scala (when I realize that the associated value is a case class, everything about them becomes meaningful). But it does not think like other functional languages. They encourage you to use let wherever possible, but in a Swift program, you will always have a mix of let and var, and most of the examples provided by Apple include variables. When working in Scala, I almost never use variable variables. In Haskell, variable variables are considered advanced features, and they do n’t even appear in introductory books.

This brings us a real difference. In Swift, you basically work in a procedural programming / object-oriented programming paradigm, and the entire language is built around this paradigm. When needed, there are tools that allow you to jump to the functional programming style (but not the full functionality of functional programming). In Haskell, you basically work in the paradigm of functional programming. There are some tools available (Monad) that allow you to jump to it when you need a procedural programming style (without the full power of procedural programming).

Someone might say: "Rob, you are too straightforward. Swift is a multi-paradigm language that includes object-oriented programming and functional programming. " Scala is a multi-paradigm, object-oriented programming / functional programming. When you deal with a problem in Scala, you break it down into objects that work primarily on immutable data structures. This is the practice of object-oriented programming / functional programming. In Swift, they are even reluctant to provide an immutable list. It's not that they can't add it, but because it's not fundamental to Swift's work.

Swift is a multi-paradigm programming language, but it is not object-oriented / functional programming. It is object-oriented / generic programming. Generic programming focuses on general algorithms that can be applied to any type. It has some similarities with functional programming, and of course there are programming languages ​​that are both functional and generic, but generic programming does not care whether the algorithm is a function (something that accepts and returns immutable values) or a process (Things that change state). You can say that Swift is not generic because it has Array <Int> (Integer Array). You can implement this structure in a non-generic language. You can also say that Swift is generic, because you can find generic programming programs in the entire core library. Consider a function like advance:

/// Return the result of moving start by n positions.  If T models
/// RandomAccessIndex, executes in O(1).  Otherwise, executes in
/// O(abs(n)).  If T does not model BidirectionalIndex, requires that n
/// is non-negative.
func advance<T : ForwardIndex>(start: T, n: T.DistanceType) -> T

This is exactly the kind of functionality you would expect from a generic language. It encapsulates an algorithm that can work on any object that implements ForwardIndex. But it is not a method that the ForwardIndex instance inherits or must implement. This may seem subtle, but it is actually a very different way of thinking.

You can see many of these things in the Swift standard library, they are exactly what you want to find in generic languages. Many things that look like "function" features are actually general algorithms. Let us look at the following quickSort and reduce functions:

func quickSort<C : MutableCollection where C.IndexType : SignedInteger>
  (inout elements: C, range: Range<C.IndexType>,
   less: (C.GeneratorType.Element, C.GeneratorType.Element) -> Bool)


func reduce<S : Sequence, U>(sequence: S, initial: U, combine: (U, S.GeneratorType.Element) -> U) -> U

Reduce is a very common functional tool, it is next to the quickSort function, but no functional language will expose it in this way (it changes the collection). Both are expressed in a generic style. They are just algorithms. One can change the collection, the other can't. The important thing is that the algorithm can be reused on a variety of data, which is generic programming. We get some functional features, but this is actually just a side effect of it, not its paradigm.

These are not criticisms of Swift. It does not matter, it is not a functional language. I had thought that it would be nice if all Cocoa development was functional programming, but it was only because I liked it. I do not know if this will further realize truly outstanding iOS and Mac application sequence of the target (at least in the short term). It's not that FRP (Functional Reactive Programming) is not a good idea. I have no strong opinions about this. But compared with Swift.2, ObjC programmer learning curve is high 2 , and we need to Swift with a (non-functional formula) ObjC integrated for a long time.

I hope that over time, Swift will include more functional features. if and switch should return values. It should allow splitting a list into heads and tails during pattern matching (this should be easy to achieve). The function should accept the "tail recursion" attribute with forced tail call optimization. Mutable methods should be used rarely, and immutable data types should be more.

None of these things make Swift itself a functional language. But enough of these things allow us to write code with more functional patterns. Perhaps one day, Swift and Cocoa can really become functional programming languages. If this is the final result, then Swift may become an unexpectedly important language that can improve programming procedures because programmers must learn functional programming to develop on a very popular platform. Learning functional programming can make you a better programmer, even if you work in other paradigms.

Or none of this will happen. Swift may just be a language for writing great iOS and Mac apps, but that ’s okay.

  1. I believe all these things will be very simple to implement in Swift. But they didn't jump out of the frame of the document, and even did not discuss these contents in any Swift video. This is a measure of what is important and what is possible. They will tell you the paradigm used.

  2. My experience with reactive UI programming in Scala has been mixed. Even with a background in functional programming, I found that my learning curve is still very high, and the program is difficult to debug. But this may just require more experience. This seems like a good idea, I just don't know if it is really a good idea.

  3. I used to ride a motorcycle. When you ride a motorcycle, you must be more sober than when driving. Otherwise, you will be injured. But what I noticed is that riding a motorcycle made me a better car driver. Functional programming is like this. Riding a motorcycle is not necessarily the best way to reach your destination, but if everyone learns to ride a motorcycle, we will have better drivers. If the university teaches Haskell first and then Java, we will have better programmers.

Original link: https://robnapier.net/swift-is-not-functional

This article is a CSDN translation article, please indicate the source.

【END】

More exciting recommendations

Taking the first place in Gartner container products, Alibaba Cloud wins the key battle of cloud native!

Tencent interviewer asked me this binary tree, I just happen to be | The Force Program

☞Winning GitHub 2000+ Star, how does Alibaba Cloud's open source Alink machine learning platform outperform the double 11 data "game"? | AI Technology Ecology

☞Microsoft acquired a company for one person? Crack Sony programs, write hacker novels, and watch his tough program life!

Machine learning project template: 6 basic steps of ML project

☞IBM, Microsoft, Apple, Google, Samsung ... These technology giants in the blockchain have already done so many things!

Summary by senior programmers: I will tell you all 6 ways to analyze the Linux process

Today's Welfare: If you leave a comment in the comment area, you can get a ticket for the live broadcast of the "2020 AI Developer Ten Thousand Conference" worth 299 yuan . Come and move your finger and write what you want to say.

Click to read the original text, wonderful to continue!

Every "watching" you order, I take it seriously

1945 original articles published · 40 thousand likes + · 18.18 million views

Guess you like

Origin blog.csdn.net/csdnnews/article/details/105445741