Skip to content

Instantly share code, notes, and snippets.

@kch
Last active July 17, 2016 20:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kch/7145cbe5429b200298a3 to your computer and use it in GitHub Desktop.
Save kch/7145cbe5429b200298a3 to your computer and use it in GitHub Desktop.
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) }
1◊add◊2
1 ◊ add ◊ 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment