Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swift functional programming function


May 21, 2021 Swift


Table of contents


Swift function programming - function

Swift supports functional programming, which describes functions in Swift.

Higher order function

A higher-order function, which refers to a function that can use other functions as arguments or return results.

The functions in Swift are high-order functions, which are consistent with Scala and Haskell. I n contrast, there are no higher-order functions in Java (Java 7 supports closure before). M ethods in Java cannot exist alone, and methods always need to be bundled with classes. W hen you need to pass one function as an argument to another, you need a class to carry the function as a carrier. This is also the practice of listeners in Java.

Higher-order functions are important for functional languages for at least two reasons:

  • First, higher-order functions mean that you can use higher abstractions because it allows us to introduce a common method of computation. F or example, you can traverse an array and apply one (or more) high-order functions to each element of it by abstracting a common mechanism. Higher-order functions can be combined into more complex higher-order functions to create deeper abstractions.

  • Second, by supporting functions as return values, you can support the construction of more dynamic and adaptable systems.

First Class Function

First-class functions further expand the scope of use of functions, making them "first-class citizens" in the language. T his means that functions can appear where any other language structure, such as a variable, appears. F irst-class functions are more stringent, higher-order functions. The functions in Swift are first-class.

Closure

A closure is a function that implicitly binds all variables it references internally. It can also be said that closures are entities that are a combination of functions and their associated reference environments.

The function is actually a special kind of closure, and you can create an anonymous closure using . Use in to split parameters and return types.

let r = 1...3
let t = r.map { (i: Int) -> Int in
    return i * 2
}

The map function traverses the array and processes all elements with closures. and returned a new array that had been processed.

Objective-C later added support for closures. C losure is a first-class function. O bjective-C expands its language skills by supporting closures. But if Swift's closure syntax is compared to Objective-C's, Swift's closure is fairly concise and elegant, and Objective-C's closure is a bit onerous and complicated.

Function Curring

Function Curring is a function that accepts multiple arguments transformed into a function that accepts a single argument (the first argument of the original function), which returns a new function that accepts the remaining arguments. T he noun comes from the logician Haskell Curring. Haskell, the programming language, also took the logician's name.

Functions in Haskell can be Curryized. T he type declaration of the function argument in Haskell also implies that the function is Curryized. I n Haskell, between the return value and the argument, the parameters are -> T his is because if you pass an argument to a function that can accept multiple arguments, the function still has a return value. I ts return value is another function. T his function can accept the remaining arguments, and we call this returned function 不全呼叫函数 Essentially, all Haskell functions have only one argument.

The following statement shows the type of Max in Haskell on the command line:

Prelude> :type max
max :: Ord a => a -> a -> a

In fact, you can also write:

max :: (Ord a) => a -> (a -> a)

This means that if a parameter a is passed to max, a function with (a -> a) returned.

Curryization makes it easy to construct new functions. It also eliminates the need to write some one-time intermediate functions.

Swift can write curry functions, although it retains a non-Curry function similar to Java. In the case of the max function, for example, the Curry function in Swift is as follows:

func max(a: Int)(b: Int) -> Int {
    return a > b ? a : b;
}

let max3 = max(3)
max3(b: 5)

Functional thinking

Use functions to solve problems

For a simple example, find out the odd number in an array of 1 to 10. Thinking using the Java language (circular control is actually the thinking of a process language), as is often the case:

var odds = [Int]()
for i in 1...10 {
    if i % 2 == 1 {
        odds.append(i)
    }
}

println(odds)

The output is: 1, 3, 5, 7, 9. Functional writing is simpler:

odds = Array(1...10).filter { $0 % 2 == 1 }
println(odds)

The simpler reason for function writing is to give up control of the loop and use functions to process sequences. H ow to handle sequences, the code that should be written in the loop body, is passed in by a function (usually a closure) in functional programming. T he concept of circular control is still used in the implementation of the language at the bottom of the computer. However, you don't need this concept when writing a functional programming language.

Another simple example, how to find out the odd numbers in an array of 1 to 10, and find their total? The usual writing would be this:

var sumOdds = 0
var odds = [Int]()
for i in 1...10 {
    if i % 2 == 1 {
        odds.append(i)
        sumOdds += i
    }
}
println(sumOdds)

The functional version would be like this:

let sum = Array(1...10)
        .myFilter { (i) in i % 2 == 1}
        .reduce(0) { (total, number) in total + number }
println(sum)

If some values in the sequence are operated on, the position of the loop can be determined in the process language because of the existence of a loop variable. T he practice of a functional programming language is to use a function to build a new sequence that meets the criteria, and Array(1...10).myFilter { (i) in i % 2 == 1} represents an odd number of 1 to 10 years. T hen take further action on the new sequence. In this example, the new reduce coupled using the reduce function.

Haskell, a purely functional programming language, has no loop control statements because it is not needed, and you don't see keywords like for, while. B ut in Swift, programmers use higher-level abstractions while giving up control of detail. H owever, this does not mean that control cannot be recycled when needed. An important aspect of functional thinking is knowing how much control to give up and when to give up.

Use function combinations

In functional programming thinking, when faced with complex problems, a combination of functions is used to model complex problems. W e use an example of determining the number of masses to represent this characteristic of functional programming. We use object-oriented programming and functional programming to implement algorithms for determining mass numbers to compare the differences between the two.

A mass is a number that can only be an integer of itself. We will use this algorithm: first find the number of the number, and then find the number of all the reasons, if all the number and add one to the number, you can determine that the number is a mass.

In order to implement the algorithm first using the usual object-oriented writing:

class PrimeNumberClassifier {

   let number: Int

   init(number: Int){
        self.number = number
   }

    func isFactor(potential: Int) -> Bool {
        return number % potential == 0
    }

    func getFactors() -> [Int] {
        var factors : [Int] = Array<Int>()
        for it in 1...number {
            if isFactor(it) {
                factors.append(it)
            }
        }
        return factors
    }

    func sumFactors() -> Int {
        let factors = getFactors()
        var sum = 0
        for factor in factors {
            sum += factor
        }
        return sum
    }

    func isPrime() -> Bool {
        return self.sumFactors() == number + 1
    }
}

Then we use functional writing:

func isFactor(number: Int)(potential: Int) -> Bool {
  return (number % potential) == 0
}

func factors(number: Int) -> [Int] {
    let isFactorForNumber = isFactor(number)
    return Array(1...number).filter {
        isFactorForNumber(potential: $0)}
}

func sumFactors(number: Int) -> Int {
    return factors(number).reduce(0){ (total, num) in 
        total + num }
}

func isPrime(number: Int) -> Bool {
    return sumFactors(number) == number + 1
}

As you can see, we have defined four functions, each of which solves a smaller problem. F inally, isPrime as the starting point, all the functions are stringed together to form the entire algorithm implementation. B ecause the functions in Swift are first-class functions. T herefore, we can use functions such as filter and reduce to accept closures to provide a more concise expression of filtering and settle. I n functional writing, all functions are stateless and have no side effects. T hat is, no matter how many times you call, as long as the input parameters of the function are determined, the output of the function is determined. B ecause there is no state, each function here is easy to reuse. You can use these functions with confidence in any external module without worrying about the effect of a state of an object on the function you call, as you do in an object-oriented language.

Summarize

The core of functional programming is functions, which are "first-class citizens". T his is like the main abstraction method of object-oriented languages is classes. F unctions in Swift have all the characteristics of functions in a functional language. This support makes it easy to write functional code using Swift.

Origin: Http://lincode.github.io/Swift-FirstOrder-Func
Author: Lin Guo