Ocaml:匹配的用法
Ocaml: usage of match with
我正在尝试在 ocaml 中编写一些代码,为预定义函数解析以下 c 代码
main {
x = function1(3);
x = function2(x,2);
}
所以这是我的 ocaml 代码:
match expr with
|Bool(b) ->( match b with
|true -> (*do things*)
|false -> (*do things*) )
|Call(f, args) ->( match f with
| function1(x) -> (*do things with x*)
| function2(x,n) -> (*do things with x and n*)
|_ -> failwith "not implemented yet " )
暂时,假设我正在解析的语言只有两个函数,我想检索 C 代码中的参数以便在我的 ocaml 程序中使用它们,但我在以下位置遇到语法错误包含与 sth()
匹配的行
删除括号和参数使程序成为 运行 但这不是我想要的,我需要参数...
我不明白我的匹配有什么问题,有人可以向我解释正确的语法吗?
提前致谢
模式匹配只匹配类型构造函数。
首先要做的是写下你要匹配的类型:
type typ =
| Bool of bool
| Function1 of int
| Function2 of int * int
那么您的函数将如下所示(将所有不同的大小写组合在一个匹配大小写中):
let eval
: typ -> unit (* The function signature *)
= fun t ->
match t with
| Bool true -> print_endline "true"
| Bool false -> print_endline "false"
| Function1 number -> print_endline (string_of_int number)
| Function2 (n1, n2) -> print_endline (string_of_int (n1 + n2))
我正在尝试在 ocaml 中编写一些代码,为预定义函数解析以下 c 代码
main {
x = function1(3);
x = function2(x,2);
}
所以这是我的 ocaml 代码:
match expr with
|Bool(b) ->( match b with
|true -> (*do things*)
|false -> (*do things*) )
|Call(f, args) ->( match f with
| function1(x) -> (*do things with x*)
| function2(x,n) -> (*do things with x and n*)
|_ -> failwith "not implemented yet " )
暂时,假设我正在解析的语言只有两个函数,我想检索 C 代码中的参数以便在我的 ocaml 程序中使用它们,但我在以下位置遇到语法错误包含与 sth()
匹配的行删除括号和参数使程序成为 运行 但这不是我想要的,我需要参数...
我不明白我的匹配有什么问题,有人可以向我解释正确的语法吗?
提前致谢
模式匹配只匹配类型构造函数。
首先要做的是写下你要匹配的类型:
type typ =
| Bool of bool
| Function1 of int
| Function2 of int * int
那么您的函数将如下所示(将所有不同的大小写组合在一个匹配大小写中):
let eval
: typ -> unit (* The function signature *)
= fun t ->
match t with
| Bool true -> print_endline "true"
| Bool false -> print_endline "false"
| Function1 number -> print_endline (string_of_int number)
| Function2 (n1, n2) -> print_endline (string_of_int (n1 + n2))