Curry Function in Swift

后端 未结 4 1639
予麋鹿
予麋鹿 2020-12-01 19:24

I want to make a function that return a curry function like below

func addTwoNumbers(a: Int)(b: Int) -> Int {
    return a + b
}

addTwoNumbers(4)(b: 6) /         


        
4条回答
  •  死守一世寂寞
    2020-12-01 19:33

    In case you want to quickly get the curry function for any number of parameters, it's possible to generate it as shown in this gist.

    The code is in Swift 2.2 and generates code for Swift 2.2 (at the moment). It uses simple template-based approach (a possible alternative is constructing an AST followed by code-generation):

    func genCurry(n: Int, indent: Indent = .fourSpaces, accessLevel: AccessLevel = .Default, verbose: Bool = false) -> String {
    
        // ...
        // The bulky park is skipped for clarity.
    
        return accessLevel.asPrefix + "func curry<\(genericParams)>(f: \(fSig)) -> \(curriedSig(n)) {\n"
            + indent.single + "return \(closure)\n"
            + "}\n"
    }
    

提交回复
热议问题