Created
November 9, 2013 23:21
-
-
Save Cergoo/7391396 to your computer and use it in GitHub Desktop.
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" | |
func collect(vals []int, f func(int) int) []int { | |
length := len(vals) | |
newVals := make([]int, length, length) | |
for i, val := range vals { | |
newVals[i] = f(val) | |
} | |
return newVals | |
} | |
func main() { | |
ints := []int{1, 2, 3, 4, 5} | |
result := collect(ints, func (a int) int { | |
return a + 1 | |
}) | |
fmt.Println(result) | |
} |
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" | |
func comb(a, b func(int) int) func(int) int { | |
return func(x int) int { | |
return a(b(x)) | |
} | |
} | |
func main() { | |
add1 := func(x int) int { | |
return x + 1 | |
} | |
add2 := func(x int) int { | |
return x + 2 | |
} | |
add3 := comb(add1, add2) | |
fmt.Println(add3(4)) | |
} |
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" | |
func partial(f func(int, int) int, a int) func(int) int { | |
return func(x int) int { | |
return f(a, x) | |
} | |
} | |
func main() { | |
add := func(a, b int) int { | |
return a + b | |
} | |
add4 := partial(add, 4) | |
fmt.Println(add4(2)) | |
} |
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" | |
func reduce(vals []int, init int, f func(int, int) int) int { | |
result := init | |
for _, val := range vals { | |
result = f(result, val) | |
} | |
return result | |
} | |
func main() { | |
ints := []int{1, 2, 3, 4, 5} | |
result := reduce(ints, 0, func (sum, i int) int { | |
return sum + i | |
}) | |
fmt.Println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment