如何评估数据类型和 true_of_all_constants 函数?

How to evaluate datatype and true_of_all_constants functions?

我是 sml 的初学者,我正在 Coursera 学习编程语言课程。有一个数据类型和函数我不知道如何计算:

datatype exp = constant of int
     | Negate of exp
     |Add of exp * exp
     |Multiply of exp * exp

fun true_of_all_constants(f,e) =
    case e of
    constant i => f i
      | Negate e1 => true_of_all_constants(f,e1)                
      | Add(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)
      | Multiply(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)

试图评估它们,我总是得到错误:

true_of_all_constants [3,4,5];
true_of_all_constants 4;
true_of_all_constants (is_even 4, 5);

其中 is_even 是一个小辅助函数:

fun is_even v =
(v mod 2 = 0)

要测试true_of_all_constants,e应该替换成什么?另外,你能解释一下数据类型在这里做什么吗?我不明白为什么我们在这里需要 "Negate" 或 "Add";为什么 "Add?"

的 "exp*exp," 而不是 "exp+exp,"

修复空白,true_of_all_constants (p, e)的数据类型定义和定义变为:

datatype exp =
    Constant of int
  | Negate of exp
  | Add of exp * exp
  | Multiply of exp * exp

fun true_of_all_constants (p, e) =
    let fun aux (Constant i)        = p i
          | aux (Negate e1)         = aux e1
          | aux (Add (e1, e2))      = aux e1 andalso aux e2
          | aux (Multiply (e1, e2)) = aux e1 andalso aux e2
    in aux e end

此处 constant 已重命名为 Constant:两者都可以使用,但使用大写字母命名构造函数可以在视觉上将其与其他标识符区分开来。我使用了一个内部函数 aux 来稍微缩短递归表达式。我把它叫做 p 而不是 f,因为 predicate,但这是一种品味。

Trying to evaluate them, I always get errors

这里有一些表达式示例和计算它们:

- val two_plus_two = Add (Constant 2, Constant 2);
- true_of_all_constants (fn i => i = 2, two_plus_two);
> val it = true : bool

- val two_times_neg_two = Multiply (Constant 2, Constant ~2);
- true_of_all_constants (fn i => i > 0, two_times_neg_two);
> val it = false : bool

- val two_four_six = Add (Constant 2, Add (Constant 4, Constant 6));
- fun is_even x = x mod 2 = 0;
- true_of_all_constants (is_even, two_four_six);
> val it = true : bool

could you explain what does datatype do here?

我想你应该在这里参考一本书或教程。

例如,ML for the Working Programmer, ch. 4(免费 PDF)涉及 datatype 个定义。

I don't understand why we need "Negate" or "Add" here

我也不知道。您在课程中遇到的问题完全是假设性的。