Curry Function in Swift

后端 未结 4 1635
予麋鹿
予麋鹿 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条回答
  •  Happy的楠姐
    2020-12-01 19:36

    I'm not sure this is actually going to be possible in the same way it is inside of languages like Python.

    The core problem I see to having a single generic solution is the strong typing of the closures/funcs you want to accept.

    You could fairly easily create a curry function that worked on a specific or common function signature, but as far as a general purpose curry I don't see a way for it to work. The issue is more than about the types of the arguments (as mentioned in comments) but also with the number of them.

    I've written up a simple example of how you could implement a curry function. It works, but I don't see a sane way to have a truly generic one like you can in more loosely typed languages.

    func add(a1: Int, a2: Int) -> Int {
        return a1 + a2
    }
    
    func curry(argument: Int, block: (Int, Int) -> Int) -> Int -> Int{
        func curried(arg: Int) -> Int {
            return block(argument, arg)
        }
    
        return curried
    }
    
    curry(5, add)(6)
    

提交回复
热议问题