Created
January 5, 2019 13:30
-
-
Save shivamMg/7610f9f5d7437b12fbd24a60fab22d3d to your computer and use it in GitHub Desktop.
Currying
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
package main | |
type VarSum func(a ...int) interface{} | |
func curry(fn func(x, y, z int) int, args ...int) interface{} { | |
if len(args) >= 3 { | |
return fn(args[0], args[1], args[2]) | |
} | |
return VarSum(func(more ...int) interface{} { | |
args = append(args, more...) | |
return curry(fn, args...) | |
}) | |
} | |
func sum(a, b, c int) int { | |
return a + b + c | |
} | |
func main() { | |
{ | |
c := curry(sum).(VarSum) | |
c1 := c(1).(VarSum) | |
c2 := c1(2).(VarSum) | |
c3 := c2(3).(int) | |
println(c3) | |
} | |
{ | |
c := curry(sum).(VarSum) | |
c1 := c(1).(VarSum) | |
c2 := c1(2, 3).(int) | |
println(c2) | |
} | |
{ | |
c := curry(sum).(VarSum) | |
c1 := c(1).(VarSum) | |
c2 := c1(2).(VarSum) | |
c3 := c2(3, 4).(int) | |
println(c3) | |
} | |
} |
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
const curry = (fn, ...args) => | |
(args.length >= fn.length) ? | |
fn(...args.slice(0, fn.length)) : | |
(...more) => curry(fn, ...args, ...more) | |
const sum = (a, b, c) => a + b + c | |
curried = curry(sum) | |
console.log(curried(1)(2)(3)) | |
console.log(curried(1)(2, 3)) | |
console.log(curried(1)(2, 3, 4)) // 4 will be ignored |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment