15

The standard SML library function Int.toString prefixes negative numbers with ~ instead of -. Is there a library function to use - instead, short of writing

fun i2s i =
    if i < 0 then "-" ^ Int.toString (~i) else Int.toString i
Jay Lieske
  • 4,788
  • 3
  • 30
  • 41
  • Note that your function will result in OverflowError in some cases, since on typical architectures, the least representable integer has greater magnitude than the greatest representable integer. (For example, 32-bit two's-complement signed integers range from ~2147483648 to 2147483647.) That may or may not be acceptable for your use-case. If it *isn't* acceptable, then one alternative is `fun i2s i = String.map (fn #"~" => #"-" | c => c) (Int.toString i)`. – ruakh Oct 11 '16 at 00:18

1 Answers1

8

In short, No.

SML is designed to use ~ for unary minus to avoid confusion with - (binary minus). It's a sensible decision when you have each operator for only one purpose and SML users have to live with that.

Although it's strange to read a string representation of an integer starting with ~, there's no library function to convert it to a string in the normal convention. BTW, your function is a good way to do so.

pad
  • 41,040
  • 7
  • 92
  • 166