Search code examples
recursionsmlsmlnjmlmutual-recursion

Tell if number is odd or even with SML


This is the second SML program I have been working on. These functions are mutually recursive. If I call odd(1) I should get true and even(1) I should get false. These functions should work for all positive integers. However, when I run this program:

fun
    odd (n) = if n=0 then false else even (n-1);
and
    even (n) = if n=0 then true else odd (n-1);

I get:

[opening test.sml]
test.sml:2.35-2.39 Error: unbound variable or constructor: even
val it = () : unit

How can I fix this?


Solution

  • The problem is the semicolon (;) in the middle. Semicolons are allowed (optionally) at the end of a complete declaration, but right before and is not the end of a declaration!

    So the compiler is blowing up on the invalid declaration fun odd (n) = if n=0 then false else even (n-1) that refers to undeclared even. If it were to proceed, it would next blow up on the illegal occurrence of and at the start of a declaration.


    Note that there are only two situations where a semicolon is meaningful:

    • the notation (...A... ; ...B... ; ...C...) means "evaluate ...A..., ...B..., and ...C..., and return the result of ...C....
      • likewise the notation let ... in ...A... ; ...B... ; ...C... end, where the parentheses are optional because the in ... end does an adequate job bracketing their contents.
    • if you're using the interactive REPL (read-evaluate-print loop), a semicolon at the end of a top-level declaration means "OK, now actually go ahead and elaborate/evaluate/etc. everything so far".

    Idiomatic Standard ML doesn't really use semicolons outside of the above situations; but it's OK to do so, as long as you don't start thinking in terms of procedural languages and expecting the semicolons to "terminate statements", or anything like that. There's obviously a relationship between the use of ; in Standard ML and the use of ; in languages such as C and its syntactic descendants, but it's not a direct one.