Search code examples
smlsmlnj

Error SML : Error: unbound variable or constructor: valof


I am taking the Programming Languages course offered by Washington University, during one of the lectures, this code popped up worked for professor Dan, however, I am getting unbound variable or constructor:valof error. Could not figure it out. it is smlnj, and running on emacs, if it would yield any help.

fun max1(xs: int list)=
    if null xs
    then NONE
    else
        let val tl_ans = max1(tl xs)
        in if isSome tl_ans andalso valof tl_ans > hd xs
            then tl_ans
            else SOME (hd xs)
        end

here is the error: options.sml:7.37-7.42 Error: unbound variable or constructor: valof


Solution

  • As quoify says, it's spelled valOf.

    And as kopecs says, if you use pattern matching, it will be much shorter:

    fun max1 (x::y::rest) = max1 (Int.max (x, y) :: rest)
      | max1 [x] = SOME x
      | max1 [] = NONE
    

    (This version also uses the library function Int.max for added brevity.)

    If this is too compact, you could also write:

    fun max1 (x::y::rest) = let val z = Int.max (x, y) in max1 (z::rest) end
      | max1 [x] = SOME x
      | max1 [] = NONE
    

    The version from the slides deals with an annoying situation that arises in many recursive functions that return sum types like 'a option: You may need to perform a call, do some unpacking (i.e. remove SOME), and then pack the result back (i.e. add SOME again).

    But the max1 problem does not necessitate that situation.