Last active
March 31, 2023 17:06
-
-
Save sug0/a9281f6bb6b09929b95ce215b721698d to your computer and use it in GitHub Desktop.
Church numerals 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
// next up: scott encoding https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding | |
package main | |
import "fmt" | |
type Church[T any] func(func(T) T) func(T) T | |
func main() { | |
churchTest[int](0, func(x int) int { return x + 1 }) | |
churchTest[[]int](nil, func(a []int) []int { return append(a, len(a)) }) | |
} | |
func churchTest[T any](init T, succ func(T) T) { | |
churchNumerals := []Church[T]{ | |
one[T](), | |
two[T](), | |
three[T](), | |
four[T](), | |
five[T](), | |
} | |
for _, church := range churchNumerals { | |
fmt.Printf("%v ", church(succ)(init)) | |
} | |
fmt.Println() | |
} | |
func zero[T any]() Church[T] { | |
return func(s func(T) T) func(T) T { | |
return func(x T) T { | |
return x | |
} | |
} | |
} | |
func succ[T any](church Church[T]) Church[T] { | |
return func(s func(T) T) func(T) T { | |
return func(x T) T { | |
return s(church(s)(x)) | |
} | |
} | |
} | |
func one[T any]() Church[T] { | |
return succ(zero[T]()) | |
} | |
func two[T any]() Church[T] { | |
return succ(one[T]()) | |
} | |
func three[T any]() Church[T] { | |
return succ(two[T]()) | |
} | |
func four[T any]() Church[T] { | |
return succ(three[T]()) | |
} | |
func five[T any]() Church[T] { | |
return succ(four[T]()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment