Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let t = (1, 2, 3) // Anonymous tuple
let n = (x: 1, y: 2, z: 3) // Named tuple
func fn(_ a : Int, _ b : Int, _ c : Int) { // Separate params
print(a, b, c)
}
func tfn(_ t: (a : Int, b : Int, c : Int)) { // Single param
print(t.a, t.b, t.c)
}
// 1: Tuple as separate args
fn(t.0, t.1, t.2)
fn(n.0, n.1, n.2)
fn(n.x, n.y, n.z)
// 2: Tuple as single arg
tfn(t)
func anon <T, U, V>(t: (T,U,V))->(T,U,V) {
return (t.0, t.1, t.2)
}
tfn(anon(n)) // Because named tuples uses different names, anonymize first
// 3: Tuple as single arg to function that takes multiple args
// 3A: Function form
func splat<T, U, V, R>(_ t : (T,U,V), _ fn: (T,U,V)->R)->R {
return fn(t.0, t.1, t.2)
}
splat(t, fn)
splat(n, fn)
// 3B: Infix Operator
infix operator ->* { associativity left }
func ->* <T, U, V, R>(_ t : (T,U,V), _ fn: (T,U,V)->R)->R {
return fn(t.0, t.1, t.2)
}
t ->* fn
n ->* fn
t ->* { (a, b, c) in print(a, b, c) }
n ->* { (a, b, c) in print(a, b, c) }
// 3C: Prefix operator
prefix operator * { }
prefix func * <T, U, V, R>(_ fn: (T,U,V)->R)->((T,U,V))->R {
return { t in fn(t.0, t.1, t.2) }
}
(*fn)(t)
(*fn)(n)
@callionica

This comment has been minimized.

Copy link
Owner Author

@callionica callionica commented May 30, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment