The main content of this article comes from the book "Functional Programming in Swift", a bit of a so-called post-view summary
In the introduction chapter of this book:
We'll try to focus on some of the qualities so we believe well-designed functional programs in Swift should exhibit:
1. Modulatity "Modular"
2. A careful treatment of Mutable State "take care of the variable condition": invariance and No side effects
3.Types "Type"
In fact, the above 3 points in my previous article has been described in detail.
thinking functionally -----Functional Programming idea, this is the second chapter of this book
Functions in Swift is first-class values
Below we illustrate the main contents of this chapter according to the examples in the book:
1. The first function we write, InRange1, checks. Checks if a point is within a range, relative to (0,0)
Determines whether the distance from the target point to the origin is <= range
Typealias Position = Cgpoint
Typealias Distance = Cgfloatfunc inRange1 (target:position, range:distance), Bool { return sqrt (target.x * targe T.x + target.y * target.y) <= Range}
2. We Now add a argument representing the location of the ship to our InRange function:
The InRange method Adds a parameter that represents the position of the ship:
Determine if the distance between two points is <= range
Func inRange2 (target:position, Ownposition:position, range:distance), Bool {let dx = ownposition.x-target.x Let -dy = ownposition.y-target.y let targetdistance = sqrt (dx * dx + dy * dy) return targetdistance <= RA Nge
Now you realize that if target is too close to you, you need to avoid it. At this point, we define a minimumdistance to represent a safe distance.
Let Minimumdistance:distance = 2.0 func inRange3 (target:position, Ownposition:position, range:distance), Bool {
let dx = ownposition.x-target.x let dy = ownposition.y-target.y let targetdistance = sqrt (dx * dx + dy * dy ) return targetdistance <= range && targetdistance >= minimumdistance}
Finally, you also need to escape from other ships that are closer to you.
Func inRange4 (target:position, Ownposition:position, Friendly:position, range:distance), Bool {let dx = OWNP Osition.x-target.x let -dy = ownposition.y-target.y let targetdistance = sqrt (dx * dx + dy * dy) let friend LYDX = friendly.x-target.x let friendlydy = friendly.y-target.y let friendlydistance = sqrt (FRIENDLYDX * frien DLYDX + friendlydy * friendlydy) return targetdistance <= range && targetdistance >= Minimumdistance && (friendlydistance >= minimumdistance)}
Functional programming of Swift (ii)-------thinking functionally