Last active
July 17, 2016 20:30
-
-
Save kch/7145cbe5429b200298a3 to your computer and use it in GitHub Desktop.
Use any binary function as infix operator 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
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) } | |
1◊add◊2 | |
1 ◊ add ◊ 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment