]> Joshua Wise's Git repositories - snipe.git/blame_incremental - util/word32.sml
Initial import of l3c
[snipe.git] / util / word32.sml
... / ...
CommitLineData
1(* L1 Compiler
2 * Utilities for signed modular arithmetic
3 * Author: Frank Pfenning
4 *)
5
6(*
7 * There are two useful structure in the SML Basis Library
8 * Int32, with 2's complement arithmetic,
9 * but it raises Overflow instead of doing modular arithmetic
10 * Word32, with unsigned modular arithmetic
11 *
12 * This structure implements some signed operations on Word32
13 *)
14
15signature WORD32_SIGNED =
16sig
17 val TMAX : Word32.word (* largest signed positive word, 2^31-1 *)
18 val TMIN : Word32.word (* smallest signed negative word -2^31 *)
19 val ZERO : Word32.word (* 0 *)
20 val fromString : string -> Word32.word option (* parse from string, no sign *)
21 (* raises Overflow if not 0 <= n < 2^32 *)
22 val toString : Word32.word -> string (* print to string, with sign *)
23end
24
25structure Word32Signed :> WORD32_SIGNED =
26struct
27 val TMIN = Word32.<<(Word32.fromInt(1), Word.fromInt(Word32.wordSize-1))
28 val TMAX = Word32.-(TMIN, Word32.fromInt(1))
29 val ZERO = Word32.fromInt(0)
30 fun neg w = Word32.>(w, TMAX)
31
32 (* fromString does not allow leading "-" *)
33 fun fromString (str) =
34 (* scanString might also raise Overflow *)
35 StringCvt.scanString (Word32.scan StringCvt.DEC) str
36
37 fun toString (w) =
38 if neg w
39 then "-" ^ Word32.fmt StringCvt.DEC (Word32.~(w))
40 else Word32.fmt StringCvt.DEC w
41end
This page took 0.025764 seconds and 4 git commands to generate.