SML - 函数计算不正确

时间:2014-04-19 21:32:58

标签: function if-statement sml

我大学的课程我必须学习SML。我现在学习了Java并且遇到了我的SML问题。我有这个功能,应该只为动物园计算一个入口费。

fun calcEntryFee (erm:bool,dauer:int,dschungel:bool,gebtag:bool):real=
let
    val c = 7.0
in
    if erm then c + 14.50 else c + 19.50;
    if dauer < 120 then c - 4.0 else c;
    if dschungel then c + 1.5 else c;
    if gebtag then c / 2.0 else c
end;

问题在于此功能会返回&#39; 7.0或3.5。但似乎没有执行其他3个if语句。

1 个答案:

答案 0 :(得分:6)

ML中没有任何陈述,只有表达式。即使A;B也是一个表达式,它会评估AB,其结果是B的结果。因此,你的前3个if-expression的结果就会被抛弃。

此外,变量是真正数学意义上的变量,因此它们是不可变的。将程序视为数学公式。

您可能想要写的内容如下:

fun calcEntryFee (erm : bool, dauer : int, dschungel : bool, gebtag : bool) : real =
let
    val fee =
        7.0
        + (if erm then 14.50 else 19.50)
        - (if dauer < 120 then 4.0 else 0.0)
        + (if dschungel then 1.5 else 0.0)
in
    if gebtag then fee / 2.0 else fee
end
相关问题