I am embedding a symbolic language in OCaml and am trying to translate my s-expression tree into an abstract syntax tree.
S-expression tree
(* 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
Abstract syntax tree
(* 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 )
The function ast_of_sexprmust match the type signature
val ast_of_sexpr : Sexpr.expr -> expr.
This is my challenge; I can’t understand the way that corresponds to the type signature, recurse into the s-expression tree (i.e. Nested Lists) and translate the nodes of the s-expression tree into abstract nodes of the syntax tree.
In an ideal world, I could evaluate the head of a list and recursion above a tail in one expression. I tried to imitate this ideal using consistency. But this, of course, ignores the left value and displays only the last value when printing the analyzed token stream.
- , s-expression? .