Created
August 12, 2016 02:56
-
-
Save d-plaindoux/0eebc5641cbc4e10889fc2b6300f61d0 to your computer and use it in GitHub Desktop.
A taste of Swift 3.0 - Peano data type design
This file contains hidden or 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 | |
public indirect enum Peano: ExpressibleByIntegerLiteral { | |
case Succ(Peano), | |
Zero | |
public init(integerLiteral v: IntegerLiteralType) { | |
if v == 0 { | |
self = .Zero | |
} else { | |
self = .Succ(Peano(integerLiteral:v - 1)) | |
} | |
} | |
public func catamorphism<R>(_ s: (Peano) -> R, _ z: () -> R) -> R { | |
switch self { | |
case .Succ(let e): | |
return s(e) | |
case .Zero: | |
return z() | |
} | |
} | |
public func add(_ p: Peano) -> Peano { | |
return catamorphism({ .Succ($0.add(p)) }, { p }) | |
} | |
public func mult(_ p: Peano) -> Peano { | |
return catamorphism({ p.add($0.mult(p)) }, { self }) | |
} | |
public func isEven() -> Bool { | |
return catamorphism({ $0.catamorphism({ $0.isEven() }, { false }) }, { true }) | |
} | |
public func _conversion() -> Int { | |
return catamorphism({ 1 + $0._conversion() }, { 0 }) | |
} | |
} | |
extension Int { | |
public init(_ p:Peano) { | |
self = p._conversion() | |
} | |
} | |
// Main | |
let r = (100 as Peano).mult(100 as Peano) | |
if r.isEven() { | |
print(String(Int(r)) + " is even!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment