ocaml - 在 Ocaml 中生成 C 代码

标签 ocaml code-generation dsl

我正在尝试在 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/

相关文章:

c# - 如何使用代码生成动态创建C#方法?

java - 使用kafka流在时间窗口中获取给定键的最后一个事件

jenkins - 如何使用 DSL [Jenkins] 写入文件?

python-3.x - 如何使用elasticsearch-dsl-py连接两个ElasticSearch索引?

recursion - 这两个递归 ocaml 函数有什么区别?

"if"语句的代码生成 - 编译器

javascript - 为什么 .replace() 不处理从 escodege.generate() 生成的大字符串?

types - OCaml 等效类型

floating-point - 在 OCaml 中,如何从字节数组创建 float ?

recursion - 通过递归函数 (Ocaml) 交错两个列表