SML:Sublime解释器工作不正确?

时间:2017-11-18 07:47:54

标签: functional-programming sublimetext3 sml smlnj sublimerepl

我正在开发SML / NY项目,我有一个数据类型expression

datatype expression =  Constant of int |
        Variable of string |
        Operator of string * expression |
        Pair of expression list |
        List of expression list

我创建了一个函数,用于求和表达式中的常量(还没有对List起作用):

fun cons [] = 0
    | cons (l) =
    case (hd l) of
        Constant a => (a + cons (tl l))
        | Operator ("*", Pair [Constant a, Constant b]) => (a*b + cons (tl l))
        | Operator ("*", List _) => (0 + cons (tl l))
        | _ => (0 + cons (tl l))

现在我正构建一个将所有Constant个表达式合并为一个的函数:

fun joinSimilar (e:expression) =
    case e of
        Operator ("+", List (l)) => Operator ("+", List [
                                    Operator ("*",List [Constant (cons (l))])
                                    ])
        | _ => Constant 0

据我了解SML,这似乎是正确的功能。但是当我测试时:

joinSimilar(joinSimilar (Operator ("+", List [
    Constant 1,
    Operator ("*", Pair [Constant 3, Constant 1]),
    Operator ("*", Pair [Constant 5, Variable "x"]),
    Variable "x",
    Operator ("*", List [Variable "x", Constant 3]),
    Operator ("*", List [Variable "x", Variable "x"])])));

我明白了:

val it = Operator ("+",List [Operator ("*",List [Constant 0])]) : expression

这不行,因为我应该得到Constant 4。诀窍是,当我只测试cons函数

cons ([Constant 1,
    Operator ("*", Pair [Constant 3, Constant 1]),
    Operator ("*", Pair [Constant 5, Variable "x"]),
    Variable "x",
    Operator ("*", List [Variable "x", Constant 3]),
    Operator ("*", List [Variable "x", Variable "x"])]);

我得到4,这是正确的结果。为什么我在第一个例子中得到0?

请帮助,我尝试了一切,我的困惑正在逐渐增长。这是Sublime的一个问题,我正在使用它?

0 个答案:

没有答案