Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created January 12, 2022 07:46
Show Gist options
  • Save VAndrJ/94e2ee111b8a2f4b9086077e4c89764a to your computer and use it in GitHub Desktop.
Save VAndrJ/94e2ee111b8a2f4b9086077e4c89764a to your computer and use it in GitHub Desktop.
Function currying
/// Currying for function with 2 arguments.
/// - Returns: A curried function (A) -> (B) -> R
public func curry<A, B, R>(_ f: @escaping (A, B) -> R) -> (A) -> (B) -> R {
{ a in { b in f(a, b) } }
}
/// Currying for function with 3 arguments.
/// - Returns: A curried function (A) -> (B) -> (C) -> R
public func curry<A, B, C, R>(_ f: @escaping (A, B, C) -> R) -> (A) -> (B) -> (C) -> R {
{ a in { b in { c in f(a, b, c) } } }
}
/// Currying for function with 4 arguments.
/// - Returns: A curried function (A) -> (B) -> (C) -> (D) -> R
public func curry<A, B, C, D, R>(_ f: @escaping (A, B, C, D) -> R) -> (A) -> (B) -> (C) -> (D) -> R {
{ a in { b in { c in { d in f(a, b, c, d) } } } }
}
/// Transforms a curried function into a function taking 2 arguments.
/// - Returns: A function (A, B) -> R
public func uncurry<A, B, R>(_ f: @escaping (A) -> (B) -> R) -> (A, B) -> R {
{ a, b in f(a)(b) }
}
/// Transforms a curried function into a function taking 3 arguments.
/// - Returns: A function (A, B, C) -> R
public func uncurry<A, B, C, R>(_ f: @escaping (A) -> (B) -> (C) -> R) -> (A, B, C) -> R {
{ a, b, c in f(a)(b)(c) }
}
/// Transforms a curried function into a function taking 4 arguments.
/// - Returns: A function (A, B, C, D) -> R
public func uncurry<A, B, C, D, R>(_ f: @escaping (A) -> (B) -> (C) -> (D) -> R) -> (A, B, C, D) -> R {
{ a, b, c, d in f(a)(b)(c)(d) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment