Skip to content

Instantly share code, notes, and snippets.

@zenna
Created April 3, 2019 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zenna/66620dd722d7b5b5c23e104099b4c8e5 to your computer and use it in GitHub Desktop.
Save zenna/66620dd722d7b5b5c23e104099b4c8e5 to your computer and use it in GitHub Desktop.
abstract type Node end
struct Val <: Node
x::Int
end
cons(::Val, x) = Val(x)
children(val::Val) = ()
struct Add{T1, T2} <: Node
a::T1
b::T2
end
cons(::Add, a, b) = Add(a, b)
children(add::Add) = (add.a, add.b)
interpret(val::Val) = val.x
interpret(add::Add) = add.a + add.b
cata_(f, node, children) = f(cons(node, map(x_ -> cata(f, x_), children)...))
cata_(f, node, children::Tuple{}) = f(node)
cata(f, node::T) where T = 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment