Ocaml中的表达 [英] Expressions in Ocaml

查看:81
本文介绍了Ocaml中的表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解表达式在Ocaml中的工作方式. 例如,我有:

I want to understand how expressions work in Ocaml. For example, I have :

type expr =
 Int of int
 | Var of string
 | Sum of expr * expr
 | Diff of expr * expr
 | Mult of expr * expr
 | Div of expr * expr

如何识别元素是否为表达式?

How can I recognise if an element is an expression?

我想到了类似expr -> expr -> bool的东西:

let subexpression express1 express2 =
 if express1 express1 then true else false 
  
 let E1 = 3 x 8 in
  let E2 = 5/6 in
   if subexpression E1 E2 then print_strin "true" else print_string "false"

我没有测试代码,因为这就是我的想法,但实际上我不知道如何编写...

I haven't test the code because this is what I'm thinking, but actually I don't know how to write it...

推荐答案

您需要弄清楚是在一般情况下询问OCaml中的表达式还是在此处定义的类型expr的值.

You need to be clear on whether you're asking about expressions in OCaml generally or values of the type expr that you define here.

因为OCaml是一种强类型语言,所以不能有格式不正确的类型expr的值.因此,没有有意义的函数来测试类型为expr的东西是否是表达式. (您可以定义一个始终返回true的函数.)

Because OCaml is a strongly typed language, you can't have a value of type expr that's not well formed. So there's no meaningful function to test whether something of type expr is an expression. (You could define a function that always returns true.)

另一方面,您建议的函数具有两个表达式参数.这也不是很有意义.这两个参数的目的是什么?

On the other hand, your proposed function has two expression parameters. This doesn't make a lot of sense either. What is the purpose of these two parameters?

问题的其他部分建议您确定一个表达式是否为另一个表达式的子表达式.完全是另一个问题.

Other parts of your question suggest that you want to determine whether one expression is a subexpression of another. That's a different question entirely.

您可以通过递归地处理不同的情况来查看类型为expr的值.用于遍历此类值的函数的基本框架如下所示:

You can look through an value of type expr by working recursively through the different cases. The basic framework of a function for traversing such a value would look something like this:

let myfunc expr =
    match expr with
    | Int n -> (* do something n, an int *)
    | Var s -> (* do something with s, a string *)
    | Sum (e1, e2) -> some_combination_of (myfunc e1) (myfunc e2)
    | Diff (e1, e2) -> some_combination_of (myfunc e1) (myfunc e2)
    | Mult (e1, e2) -> some_combination_of (myfunc e1) (myfunc e2)
    | Div (e1, e2) -> some_combination_of (myfunc e1) (myfunc e2)

很难说更多的话,因为您的问题很难理解(坦率地说,您似乎还没有做很多工作).

It's hard to say more than this because your question is hard to understand, (and it frankly doesn't look like you've put in very much work on it yet).

这篇关于Ocaml中的表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆