Skip to content

Instantly share code, notes, and snippets.

@dysinger
Created June 3, 2014 00:16
Show Gist options
  • Save dysinger/b820a06a26cc42a304a6 to your computer and use it in GitHub Desktop.
Save dysinger/b820a06a26cc42a304a6 to your computer and use it in GitHub Desktop.
One of these things is not like the other.
-- Currying in Haskell
add :: Int -> Int -> Int -> Int -> Int
add a b c d = a + b + c + d
-- use `add 3 7 9 11`
// Currying in Swift
func add(a: Int) -> (Int -> Int) {
func add1(b: Int) -> (Int -> Int) {
func add2(c: Int) -> (Int -> Int) {
func add3(d: Int) -> Int {
return a + b + c + d
}
return add3
}
return add2
}
return add1
}
// use `add(3)(7)(9)(11)`
// JavaScript Currying
function add(a) {
return function(b) {
return function(c) {
return function(d) {
return a + b + c + d;
}
}
}
}
// use `add(3)(7)(9)(11)`
Copy link

ghost commented Jun 7, 2014

There turns out to be lambda/dot type syntax in swift also, so this works:

func add(a:Int) -> Int -> Int -> Int -> Int {
    return { b in return { c in return { d in return a + b + c + d } } }
}

add(3)(7)(9)(11)

Still figuring out the extent of the type inference.....

@mark
Copy link

mark commented Jun 9, 2014

Swift also supports:

func add(a:Int)(b:Int)(c:Int)(d:Int) -> Int {
  return a + b + c + d
}

@texastoland
Copy link

👍 …which is impressively close to Haskell and syntactically equivalent to what I remember in Scala:

def add(a:Int)(b:Int)(c:Int)(d:Int) = a + b + c + d

@st32lthx
Copy link

Shouldn't the first definition be like this ?

func add(a: Int) -> Int -> Int -> Int -> Int{
    func add1(b: Int) -> Int -> Int -> Int {
        func add2(c: Int) -> Int -> Int {
            func add3(d: Int) -> Int {
                return a + b + c + d
            }
            return add3
        }
        return add2
    }
    return add1
}

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