swift之函數式編程(二)------- Thinking Functionally

來源:互聯網
上載者:User

標籤:

本文的主要內容來自《Functional Programming in Swift》這本書,有點所謂的觀後總結

在本書的Introduction章中:

we will try to focus on some of the qualities that we believe well-designed functional programs in Swift should exhibit: 

1. Modulatity【模組化】

2. A Careful Treatment of Mutable State 【細心對待可變的狀態】: 不變性和無副作用

3.Types【類型】

其實上面的3點在我上篇文章已經詳細介紹了。

 

Thinking Functionally  ----- 函數式編程思想,這是本書的第二章

Functions in Swift are first-class values 

下面我們根據書中的例子來闡述下本章的主要內容:

1. The first function we write, inRange1, checks that a point is in the grey。核查一個point是否在某個範圍內,相對於(0,0)

判斷目標點到原點的距離是不是<= range

 

 

 

 

 

 

 

 

 

 

 

 

typealias Position = CGPoint 
typealias Distance = CGFloatfunc inRange1(target: Position, range: Distance) -> Bool { return sqrt(target.x * target.x + target.y * target.y) <= range}

 2. We now add an argument representing the location of the ship to our inRange function: 

inRange方法中增加一個代表船的位置的參數:

判斷兩個點之間的距離是不是<= 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 <= range}

現在你意識到如果target 理你太近了你要躲避它。這個時候我們定義一個minimumDistance 來代表安全距離

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}

最後,你也需要去逃離 其他的離你比較近的ships。

func inRange4(target: Position, ownPosition: Position, friendly: Position, range: Distance) -> Bool {    let dx = ownPosition.x - target.x    let dy = ownPosition.y - target.y    let targetDistance = sqrt(dx * dx + dy * dy)    let friendlyDx = friendly.x - target.x    let friendlyDy = friendly.y - target.y    let friendlyDistance = sqrt(friendlyDx * friendlyDx + friendlyDy * friendlyDy)    return targetDistance <= range              && targetDistance >= minimumDistance              && (friendlyDistance >= minimumDistance)}               

  

 

 

 

 

  

swift之函數式編程(二)------- Thinking Functionally

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.