Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Use any binary function as infix operator in Swift
infix operator « { precedence 131 associativity left }
func «<A,B,C>(a:A, f:(A,B) -> C) -> B -> C { return { f(a,$0) } }
infix operator » { precedence 131 associativity left }
func »<B,C>(f:(B) -> C, b:B) -> C { return f(b) }
infix operator < { precedence 131 associativity left }
func <<A,B,C>(a:A, f:(A,B) -> C) -> B -> C { return { f(a,$0) } }
infix operator > { precedence 131 associativity left }
func ><B,C>(f:(B) -> C, b:B) -> C { return f(b) }
func add(a:Int,b:Int) -> Int { return a + b }
func mul(a:Int,b:Int) -> Int { return a * b }
// working with two options for the same thing:
1«add»2
1<add>2
5«add»3 == 2<mul>4 // -> true
1 < add > 2 // -> 3
// because not a real operator, can't set custom precedences
1«add»2«mul»3 // -> 9, not 7 as (1+2*3) would have given you
// (a <f> b) doesn't work because < is treated as prefix and > as postfix.
// so either no spaces at all or spaces everywhere
// or using the same character:
infix operator { precedence 131 associativity left }
func <A,B,C>(a:A, f:(A,B) -> C) -> B -> C { return { f(a,$0) } }
func <B,C>(f:(B) -> C, b:B) -> C { return f(b) }
1add2
1 add 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment