Skip to content

Instantly share code, notes, and snippets.

@marksands
Last active May 8, 2019 01:58
Show Gist options
  • Save marksands/46967937901a715c9ff4aa2cafc11e84 to your computer and use it in GitHub Desktop.
Save marksands/46967937901a715c9ff4aa2cafc11e84 to your computer and use it in GitHub Desktop.
enum Direction {
case up, down, left, right
}
protocol PositionType {
var x: Int { get }
var y: Int { get }
}
func euclideanDistance(_ lhs: PositionType, _ rhs: PositionType) -> Double {
return sqrt(pow(Double(rhs.x - lhs.x), 2) + pow(Double(rhs.y - lhs.y), 2))
}
let moves = [Direction.left, .up, .up, .up, .right, .right]
class MutatingPosition: CustomDebugStringConvertible {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
func move(direction: Direction) {
switch direction {
case .down: y += 1
case .up: y -= 1
case .left: x -= 1
case .right: x += 1
}
}
var debugDescription: String {
return "Position(x: \(x), y: \(y))"
}
}
let startingPosition_mutating = MutatingPosition(x: 5, y: 5)
//let startingPosition2 = startingPosition_mutating // This is a bug. Reference semantics.
let startingPosition2 = MutatingPosition(x: startingPosition_mutating.x, y: startingPosition_mutating.y)
moves.forEach {
startingPosition_mutating.move(direction: $0)
}
// our destination is, unfortunately, also our "starting position"
lets destination2 = startingPosition_mutating
print("Euclidian Distance of mutating class:")
print(euclideanDistance(startingPosition2, destination2))
struct Position: PositionType {
let x: Int
let y: Int
}
func navigate(_ direction: Direction) -> (Position) -> (Position) {
return { position in
switch direction {
case .down: return Position(x: position.x, y: position.y + 1)
case .up: return Position(x: position.x, y: position.y - 1)
case .left: return Position(x: position.x - 1, y: position.y)
case .right: return Position(x: position.x + 1, y: position.y)
}
}
}
let startingPosition = Position(x: 5, y: 5)
let destination = moves
.map { navigate($0) }
.reduce(startingPosition) { $1($0) }
print("Euclidian Distance of curried structs:")
print(euclideanDistance(startingPosition, destination))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment