Created
February 25, 2025 11:30
-
-
Save brendanzab/79b659db0e08962d8f732c9ff99cf1af to your computer and use it in GitHub Desktop.
Folding over an AST using recursion schemes (a response to https://bsky.app/profile/bandukwala.me/post/3liwrjfotek2a).
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
module Expr = struct | |
module Layer = struct | |
type 'a t = | |
| Mul of 'a * 'a | |
| Add of 'a * 'a | |
| Int of int | |
let map (f : 'a -> 'b) (layer : 'a t) : 'b t = | |
match layer with | |
| Mul (x, y) -> Mul (f x, f y) | |
| Add (x, y) -> Add (f x, f y) | |
| Int x -> Int x | |
end | |
type t = { | |
layer : t Layer.t; | |
} | |
(* See https://hackage.haskell.org/package/recursion-schemes-5.2.3/docs/Data-Functor-Foldable.html#v:fold *) | |
let rec fold (f : 'a Layer.t -> 'a) (expr : t) : 'a = | |
f (Layer.map (fold f) expr.layer) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment