我正在尝试在 OCaml 中创建一个代码生成 DSL,但是我找不到很多关于代码生成的示例。我只是想看看如何在 OCaml 中创建代码值。
例如,如果我有这样的类型:
let equation =
Add of int * int
| Sub of int * int
| Mul of int * int
| Div of int * int;;
我想要一个这样的函数:
let write_code = function
| Add (x, y) -> // INSERT CODE "x + y" here
等等...这看起来怎么样?
我看过这个例子http://okmij.org/ftp/meta-programming/tutorial/power.ml但字符.< >。当我尝试编译时导致语法错误。
生成的代码不需要编译或执行,而是保存到.c文件中供以后使用。
我只是想看看这个简单示例的基本结构,以便我可以将其应用于更复杂的问题。
最佳答案
你可以这样做:
type equation =
| Const of int
| Var of string
| Add of equation * equation
| Mul of equation * equation ;;
let rec c_string_of_equation = function
| Const i -> string_of_int i
| Var x -> x
| Add (e1, e2) ->
"(" ^ c_string_of_equation e1 ^ ") + (" ^ c_string_of_equation e2 ^ ")"
| Mul (e1, e2) ->
"(" ^ c_string_of_equation e1 ^ ") * (" ^ c_string_of_equation e2 ^ ")"
;;
在这里,您生成一个字符串,然后您可以将该字符串写入您想要的位置。
我稍微改变了你的表达类型,使其更加通用。
结果字符串将包含太多括号,但这并不重要,因为生成的代码不是针对人类而是针对编译器。
关于ocaml - 在 Ocaml 中生成 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928288/