Question

for a course at my university I have to learn SML. I learnd java befor and having my problems with SML now. I have this function that should simply calculates an entryfee for a zoo.

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;

The problem is that this function 'returns' 7.0 or 3.5. But doesn't seem to execute the other 3 if-statements.

Was it helpful?

Solution

There are no statements in ML, only expressions. Even A;B is an expression, which evaluates A and B and whose result is the result of B. Consequently, the result of your first 3 if-expressions is just thrown away.

Also, variables are variables in the true math sense, so they are immutable. Think of a program as a mathematical formula.

What you probably want to write is something like the following:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top