Created
October 27, 2014 22:07
-
-
Save mbrandonw/f2e7e3b65d6fad35131e to your computer and use it in GitHub Desktop.
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 | |
/** | |
Num typeclass | |
*/ | |
protocol Num { | |
func + (lhs: Self, rhs: Self) -> Self | |
func - (lhs: Self, rhs: Self) -> Self | |
func * (lhs: Self, rhs: Self) -> Self | |
func / (lhs: Self, rhs: Self) -> Self | |
func % (lhs: Self, rhs: Self) -> Self | |
init(_ v: Int) | |
} | |
/** | |
Partial application of * and + | |
*/ | |
prefix operator * {} | |
prefix func * <A: Num> (x: A) -> A -> A { | |
return { $0 * x } | |
} | |
postfix operator * {} | |
postfix func * <A: Num> (x: A) -> A -> A { | |
return { x * $0 } | |
} | |
prefix operator + {} | |
prefix func + <A: Num> (x: A) -> A -> A { | |
return { $0 + x } | |
} | |
postfix operator + {} | |
postfix func + <A: Num> (x: A) -> A -> A { | |
return { x + $0 } | |
} | |
/** | |
Extensions of core data types | |
*/ | |
extension Double : Num {} | |
extension Float : Num {} | |
extension Int : Num {} | |
extension Int8 : Num {} | |
extension Int16 : Num {} | |
extension Int32 : Num {} | |
extension Int64 : Num {} | |
extension UInt : Num {} | |
extension UInt8 : Num {} | |
extension UInt16 : Num {} | |
extension UInt32 : Num {} | |
extension UInt64 : Num {} |
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
func square <A: Num> (x: A) -> A { | |
return x * x | |
} | |
square(5) //=> 25 | |
square(1.5) //=> 2.25 | |
let xs = [1, 1, 2, 3, 5, 8] | |
map(xs, *3) //=> [3, 3, 6, 9, 15, 24] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment