Created
April 12, 2015 07:45
-
-
Save minsOne/416344202593cfe64b99 to your computer and use it in GitHub Desktop.
Functional Programming Example in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
typealias Position = CGPoint | |
typealias Distance = CGFloat | |
typealias Region = Position -> Bool | |
func inRange1(target: Position, range: Distance) -> Bool { | |
return sqrt(target.x * target.x + target.y * target.y) <= range | |
} | |
func circle(radius: Distance) -> Region { | |
return { point in | |
sqrt(point.x * point.x + point.y + point.y) <= radius | |
} | |
} | |
func shift(offset: Position, region: Region) -> Region{ | |
return { point in | |
let shiftedPoint = Position(x: point.x - offset.x, y: point.y - offset.y) | |
return region(shiftedPoint) | |
} | |
} | |
func invert(region: Region) -> Region { | |
return { point in | |
!region(point) | |
} | |
} | |
func intersection(region1: Region, region2: Region) -> Region { | |
return { point in | |
region1(point) && region2(point) | |
} | |
} | |
func union(region1: Region, region2: Region) -> Region { | |
return { point in | |
region1(point) || region2(point) | |
} | |
} | |
func difference(region: Region, minusRegion: Region) -> Region { | |
return intersection(region, invert(minusRegion)) | |
} | |
let minimumDistance: Distance = 2.0 | |
func inRange(#ownPosition: Position, #target: Position, #friendly: Position, #range: Distance) -> Bool{ | |
let rangeRegion = difference(circle(range), circle(minimumDistance)) | |
let targetRegion = shift(ownPosition, rangeRegion) | |
let friendlyRegion = shift(friendly, circle(minimumDistance)) | |
let resultRegion = difference(targetRegion, friendlyRegion) | |
return resultRegion(target) | |
} | |
inRange(ownPosition: Position(x: 5, y: 5), target: Position(x: 8, y: 8), friendly: Position(x: 1, y: 1), range: 10) // true | |
inRange(ownPosition: Position(x: 5, y: 5), target: Position(x: 6, y: 6), friendly: Position(x: 1, y: 1), range: 10) // false | |
inRange(ownPosition: Position(x: 5, y: 5), target: Position(x: 8, y: 8), friendly: Position(x: 7, y: 7), range: 10) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment