Search code examples
if-statementsyntaxsmllet

nested let and if statements


I am having issues understanding SML's syntax for nested lets and ifs. For example, why is this syntactically ill-formed?

fun stuff a =
  let
      val p = 2
  in
      if a = 1
      then
      let 
          val r = p 
      in
          a = r
      end
      else
      0
  end

if a is 1 then make a equal tor, if a is not 1, then do not create r in the first place and return 0. Kinda stupid, but o well...

So, why is this syntactically incorrect?


Solution

  • It is not syntactically incorrect. It is however a type error.

    The problem is that both branches of an if need to have the same type, whereas your then-branch has the type bool (a = b is a comparison, not an assignment, but if it were an assignment, it'd have type unit, which is also the wrong type) and your else-branch has type int. You can make your code compile by returning a boolean in the else branch like this:

    fun stuff a =
      let
        val p = 2
      in
        if a = 1
        then
          let 
            val r = p 
          in
            a = r
          end
        else
          false
      end
    

    PS: Note that you can only assign to refs in SML, so if you wanted to assign to a in your code, you'd need to make it an int ref rather than a plain int.