Last active
April 3, 2019 05:19
-
-
Save zenna/89a2749dc9982379ab0e55e0c2219519 to your computer and use it in GitHub Desktop.
Catamorphism
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
# Simplest Version | |
abstract type Node end | |
struct Val <: Node | |
x::Int | |
end | |
children(val::Val) = () | |
struct Add <: Node | |
a | |
b | |
end | |
children(add::Add) = (add.a, add.b) | |
interpret(val::Val) = val.x | |
interpret(add::Add) = add.a + add.b | |
cata_(f, node::T, children) where T = f(T(map(x_ -> cata(f, x_), children)...)) | |
cata_(f, node, children::Tuple{}) = f(node) | |
cata(f, node) = cata_(f, node, children(node)) | |
term = Add(Add(Val(1), Val(2)), Val(3)) | |
cata(interpret, term) | |
swap(add::Add) = Add(add.b, add.a) | |
swap(v::Val) = v | |
cata(swap, term) |
Author
zenna
commented
Apr 3, 2019
With the implementation I wrote I don't think it should be Val(v), that would double up the Vals
I misread the code. I deleted that comment before I saw your reply.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment