Created
November 20, 2016 07:28
-
-
Save jochasinga/13545edada43b46287802a3dd9b5c465 to your computer and use it in GitHub Desktop.
Example of currying (higher order functions) in Go
This file contains 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 | |
import "fmt" | |
type List struct { | |
Inner []int | |
} | |
func NewList(s []int) List { | |
return List{Inner: s} | |
} | |
func (li List) Map(fn func(int) int) (List) { | |
out := []int{} | |
for _, num := range li.Inner { | |
num = fn(num) | |
out = append(out, num) | |
} | |
return List{Inner: out} | |
} | |
func main() { | |
multiply := func(a int) (func(int) int) { | |
return func(b int) int { | |
return a * b | |
} | |
} | |
fmt.Println(multiply(2)(3)) // 6 | |
nums := []int{1, 3, 5, 9} | |
li := NewList(nums) | |
list1 := li.Map(multiply(2)) | |
list2 := li.Map(multiply(10)) | |
fmt.Println(list1) // [2, 6, 5, 9] | |
fmt.Println(list2) // [10, 30, 50, 90] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment