Last active
January 19, 2016 02:56
-
-
Save rhysforyou/30dd5ab67cf522a4d1c2 to your computer and use it in GitHub Desktop.
Partial application in Swift
This file contains hidden or 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
| //: Playground - noun: a place where people can play | |
| import Foundation | |
| func apply<A, B>(fn: (A) -> B, _ a: A) -> B { | |
| return fn(a) | |
| } | |
| func apply<A, B, C>(fn: (A, B) -> C, _ a: A) -> B -> C { | |
| return { b in return fn(a, b) } | |
| } | |
| func apply<A, B, C>(fn: (A, B) -> C, _ a: A, _ b: B) -> C { | |
| return fn(a, b) | |
| } | |
| func apply<A, B, C, D>(fn: (A, B, C) -> D, _ a: A) -> (B, C) -> D { | |
| return { b, c in return fn(a, b, c) } | |
| } | |
| func apply<A, B, C, D>(fn: (A, B, C) -> D, _ a: A, _ b: B) -> C -> D { | |
| return { c in return fn(a, b, c) } | |
| } | |
| func apply<A, B, C, D>(fn: (A, B, C) -> D, _ a: A, _ b: B, _ c: C) -> D { | |
| return fn(a, b, c) | |
| } | |
| func apply<A, B, C, D, E>(fn: (A, B, C, D) -> E, _ a: A) -> (B, C, D) -> E { | |
| return { b, c, d in return fn(a, b, c, d) } | |
| } | |
| func apply<A, B, C, D, E>(fn: (A, B, C, D) -> E, _ a: A, _ b: B) -> (C, D) -> E { | |
| return { c, d in return fn(a, b, c, d) } | |
| } | |
| func apply<A, B, C, D, E>(fn: (A, B, C, D) -> E, _ a: A, _ b: B, _ c: C) -> D -> E { | |
| return { d in return fn(a, b, c, d) } | |
| } | |
| func apply<A, B, C, D, E>(fn: (A, B, C, D) -> E, _ a: A, _ b: B, _ c: C, _ d: D) -> E { | |
| return fn(a, b, c, d) | |
| } | |
| let addTwo = apply(+, 2) | |
| addTwo(3) // => 5 | |
| [1, 2, 3, 4, 5].map(apply(*, 2)) // => [2, 4, 6, 8, 10] | |
| class Greeter { | |
| let greeting: String | |
| init(greeting: String = "Hello") { | |
| self.greeting = greeting | |
| } | |
| func greet(name: String = "World") -> String { | |
| return "\(greeting), \(name)" | |
| } | |
| } | |
| func apply<A, B, C>(fn: A -> B -> C, a: A) -> B -> C { | |
| return { b in fn(a)(b) } | |
| } | |
| let greeter = Greeter() | |
| let greetFn = apply(Greeter.greet, greeter) | |
| greetFn("World") // Hello, world |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment