views:

206

answers:

2

Is there a way to print polymorphic values in Standard ML (SML/NJ specifically)? I have a polymorphic function that is not doing what I want and due to the abysmal state that is debugging in SML (see Any real world experience debugging a production functional program?), I would like to see what it is doing with some good-ol' print's. A simple example would be (at a prompt):

fun justThisOnce(x : 'a) : 'a = (print(x); x);
justThisOnce(42);

Other suggestions are appreciated. In the meantime I'll keep staring the offending code into submission.

Update

I was able to find the bug but the question still stands in the hopes of preventing future pain and suffering.

A: 

Only in MOSML: Merely for debugging purposes, use the printVal function. Note that this function is only available in toplevel mode, it will cause an error when you try to compile your program.

Edit: In that case, I'm afraid there is no general solution, you need to translate your values explicitly to strings, and print those. See other answer for good suggestions.

David Hanak
Looks like printVal is only available in Moscow ML http://www.itu.dk/~sestoft/mosmllib/Meta.html. Unfortunately I'm stuck with SML/NJ, but thanks for the suggestion.
Andrew Keeton
+3  A: 

No, there is no way to print a polymorphic value. You have two choices:

  • Specialize your function to integers or strings, which are readily printed. Then when the bug is slain, make it polymorphic again.

  • If the bug manifests only with some other instantiation, pass show as an additional argument to your function. So for example, if your polymorphic function has type

    'a list -> 'a list
    

    you extend the type to

    ('a -> string) -> 'a list -> 'a list
    

    You use show internally to print, and then by partially applying the function to a suitable show, you can get a version you can use in the original context.

    It's very tedious but it does help. (But be warned: it may drive you to try Haskell.)

Norman Ramsey