Last active
September 25, 2017 05:17
-
-
Save kechan/32b7f8eae9cb23a22f1e099bac14d7b7 to your computer and use it in GitHub Desktop.
Math-like Operators 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
// Paste this in Playground | |
infix operator ∘ | |
prefix operator ∑^ | |
typealias ItoD = (Int) -> Double | |
func *(lhs: Int, rhs: Double) -> Double { | |
return Double(lhs)*rhs | |
} | |
func *(lhs: Double, rhs: Int) -> Double { | |
return Double(rhs) | |
} | |
prefix func ∑^(range: @escaping ()->CountableRange<Int>) -> ((@escaping ItoD) -> ()->Double) { | |
return {f in | |
return { | |
var sum = 0.0 | |
for i in range() { | |
sum += f(i) | |
} | |
return sum | |
} | |
} | |
} | |
func ∘(lhs: ((@escaping ItoD) -> ()->Double), rhs: @escaping ItoD) -> Double { | |
return lhs(rhs)() | |
} | |
let square = { (x: Int) in Double(x*x) } | |
let sum = ∑^{0..<4}∘square | |
sum | |
let sum2 = ∑^{0..<10}∘{ Double($0 * $0) } | |
sum2 | |
let π = Double.pi | |
let trig_sum = ∑^{0..<100}∘{ sin($0 * π/4.0) } // sin(iπ/4) | |
trig_sum | |
// Indefinite sum | |
prefix func ∑(f: @escaping ItoD) -> (() -> CountableRange<Int>) -> Double { | |
return { | |
range in | |
var sum = 0.0 | |
for i in range() { | |
sum += f(i) | |
} | |
return sum | |
} | |
} | |
func ∘(lhs: (() -> CountableRange<Int>) -> Double, rhs: @escaping ()->CountableRange<Int>) -> Double { | |
return lhs(rhs) | |
} | |
let an_indefinite_sum = ∑square | |
let a_sum = an_indefinite_sum∘{0..<3} | |
a_sum | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment