Created
September 10, 2017 07:06
-
-
Save davidpaulhunt/f2dcb8e89513025e5e8264358417f898 to your computer and use it in GitHub Desktop.
Basic currying in Go
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
// Go Playground: https://play.golang.org/p/6C9Wj8uqmc | |
package main | |
import "fmt" | |
func increment(x int) int { | |
return x + 1 | |
} | |
func decrement(x int) int { | |
return x - 1 | |
} | |
func handler(s string) func(int) int { | |
return func(x int) int { | |
if s == "success" { | |
return increment(x) | |
} | |
return decrement(x) | |
} | |
} | |
func done(s string, x int) int { | |
return handler(s)(x) | |
} | |
func main() { | |
var x int | |
x = done("success", x) | |
fmt.Printf("Expected 1, got %v\n", x) | |
x = done("failure", x) | |
fmt.Printf("Expected 0, got %v\n", x) | |
x = done("success", x) | |
fmt.Printf("Expected 1, got %v\n", x) | |
x = done("success", x) | |
fmt.Printf("Expected 2, got %v\n", x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment