Created
June 19, 2020 04:03
-
-
Save agarman/24286cc9d561b7cbfe65b2700a44cbc4 to your computer and use it in GitHub Desktop.
Go 2 Generics -- https://go2goplay.golang.org/p/vW7-88vRFzj
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 main() { | |
fmt.Printf("%#v\n", Identity('a')) | |
fmt.Printf("%#v\n", Identity(Box('a'))) | |
fmt.Printf("%#v\n", Identity(Unbox(Box('a')))) | |
fmt.Printf("%#v\n", Apply(Identity(rune), 'a')) | |
} | |
// Identity function | |
func Identity(type A)(id A) A { return id } | |
// Ref cell for boxing values | |
type Ref(type A) struct{ value *A } | |
// Box a value | |
func Box(type A)(value A) Ref(A) { return Ref(A){&value} } | |
// Unbox a value | |
func Unbox(type A)(box Ref(A)) A { return *box.value } | |
// Apply a function to an arg | |
func Apply(type A, B)(f func(A) B, a A) B { return f(a) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment