How can I print a non-string in sml?
As I understand it, this is not possible (in a portable way). Depending on the implementation you're using it may expose a function that does this.
Also how can I print other non-string objects such as true
and false
?
Many types with corresponding basis library structures (e.g., int
and Int
) have a toString
function, so you could print a bool b
via print (Bool.toString b)
and similarity with Int.toString
for an int
.
Some implementation specific thoughts:
For PolyML, you can use the function PolyML.print
to print values of arbitrary types (though you may need to explicitly type annotate; the type of the argument should not have any type variables).
For SML/NJ, you might try taking a look at the approach discussed here https://sourceforge.net/p/smlnj/mailman/message/21897190/, though this seems like more trouble than it's worth.
For MLton, I'm not aware of anything like a polymorphic function, but they have a couple guides on implementing printf or similar.
It looks like Moscow ML supports a function Meta.printVal
, but only in an interactive session. I'm not sure what support SML# has for this sort of thing.
Am I responsible for writing a function which converts such an object to a string, and then print the string?
Generally speaking, yes.
It would appear that sml knows how to print such objects
Depending on your SML implementation this is enabled because the REPL has access to more information than a program normally might. For instance, SML/NJ is able to do this because the REPL has access to type information not available elsewhere (for a source, see John Reppy's statements in the linked mailman thread).
You might also find MLton's TypeIndexedValues example page helpful for this sort of thing, though I haven't closely examined it for quality myself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…