Friday, July 04, 2008

Typing SML values

I recently spent a few weeks learning the basics of Haskell.
One of the many strengths is the ability to give the types
of functions in a structure. This seems like a necessary
feature, but it is lacking in SML and O'Caml. For instance,
in Haskell I can write

incr :: Int -> Int
incr x = x + 1

In ML I'd either write

fun incr x = x + 1

and hope I can do the static typing in my head, or else
the horrible

fun incr (x : int) : int = x + 1

Note that it is possible to give incr a type in a
signature, but if I don't want to expose incr (it's
just used in the implementation), I'm out of luck.
While this example may not be entirely convincing, when
functions take many arguments, and are nested, it becomes
increasingly difficult to do mental type checking.

A hack to do this in SML is

fun incr x = x + 1
val incr : int -> int = incr

in O'Caml

let incr x = x + 1
let incr : int -> int = incr

Granted, this is not nearly as nice, but ML will catch
type errors this way.

3 comments:

  1. I've started using the idiom

    let x : int -> int =
    fn x => x + 1

    of course, this only works with non-recursive functions.

    ReplyDelete
  2. Thanks rob. This gave me the idea I should have thought of a long time ago:

    val rec fib : int -> int =
    fn 0 => 1
    | n => n * fib (n-1)

    ReplyDelete