OCaml でシンボリック言語を実装しており、S 式ツリーを抽象構文ツリーに変換するのに苦労しています。
s式ツリーは
(* sexpr.mli *)
type atom =
| Atom_unit
| Atom_int of int
| Atom_sym of string
type expr =
| Expr_atom of atom
| Expr_list of expr list
抽象構文木は
(* ast.ml *)
open Sexpr
type sym = string
(* abstract syntax tree nodes *)
type expr =
| Expr_unit
| Expr_int of int
| Expr_sym of sym
(* Sexp.atom -> Ast.expr *)
let ast_of_atom a =
match a with
| Atom_unit -> Expr_unit
| Atom_int n -> Expr_int n
| Atom_sym s -> Expr_sym s
(* Sexp.expr -> Ast.expr *)
let rec ast_of_sexpr sx = match sx with
| Expr_atom a -> ast_of_atom a
| Expr_list l ->
match l with
| [] -> ast_of_atom Atom_unit
| [x] -> ast_of_sexpr x
| h::t -> ignore ( ast_of_sexpr h ); ast_of_sexpr ( Expr_list t )
関数ast_of_sexpr
は型シグネチャに準拠する必要があります
val ast_of_sexpr : Sexpr.expr -> expr
.
これは私の挑戦です。型シグネチャに準拠し、s-expression ツリー (つまり、ネストされたリスト) に再帰し、s-expression ツリー ノードを抽象構文ツリー ノードに変換する方法がわかりません。
理想的な世界では、1 つの式でリストの先頭を評価し、末尾を再帰できます。シーケンスを使用して、この理想をエミュレートしようとしました。しかしもちろん、これは左側の値を無視し、解析されたトークンのストリームを出力するときに最後の値のみを出力します。
value を無視せずにリスト ヘッドを評価し、s-expression ツリーを深く再帰する方法を提案できる人はいますか? 私は、2 つのツリー間を変換するためのより良い解決策を読むことにもオープンです。