Skip to content

Instantly share code, notes, and snippets.

@callionica
Last active May 5, 2017 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callionica/43f79dd0a9b145746d72e8a8a62c2820 to your computer and use it in GitHub Desktop.
Save callionica/43f79dd0a9b145746d72e8a8a62c2820 to your computer and use it in GitHub Desktop.
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
Copy link
Author

callionica commented May 30, 2016

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