1 datatype 'a Option
= None | Some
of 'a
3 fun digit n
= chr(ord #
"0" + n
)
5 if n
>=0 andalso n
<=9 then digit n
:: acc
6 else digits (n
div 10, digit(n
mod 10) :: acc
)
8 fun toString(n
) = implode(digits(n
,[]))
10 fun writeln s
= print(s^
"\n")
12 fun percent(i
: int, j
: int)(*:int*) =
13 floor((real i
* 100.0)/real j
)
15 (* seek
: (char
-> bool) -> instream
-> string list
:
16 seek(pred
)(is
) returns the list
of characters obtained
17 by reading from up to
and including the first character
18 which satisfies
"pred". (If no such character exists
, the
19 empty list is returned
.
22 fun seek (pred
: char
-> bool) (is
: TextIO.instream
): char list
=
24 (case explode (TextIO.inputN(is
, 1)) of
26 |
[char
] => char
:: (if pred char
then []
28 | _
=> (print
"lib.seek: impossible"; raise Impossible
))
32 fun readLn(is
) = seek(fn ch
=> ch
= #
"\n")is
34 (* dropwhile
: ('a
-> bool) -> 'a list
-> 'a list
; endomorphic
*)
35 fun dropwhile pred l
=
36 let fun drop_loop (l
as []) = l
37 |
drop_loop (l
as x
::xs
) =
38 if pred x
then drop_loop xs
else l
42 (* takewhile
: ('a
-> bool) -> 'a list
-> 'a list
; exomorphic
*)
43 fun takewhile pred l
=
44 let fun take_loop
[] = []
45 |
take_loop (l
as x
::xs
) =
46 if pred x
then x
:: take_loop xs
else []
50 fun isSpace(ch
:char
) =
51 ch
= #
" " orelse ch
= #
"\t" orelse ch
= #
"\n"
52 (* orelse ch
= "\f" orelse ch
= "\r" orelse ch
= "\v"*)
54 fun readWord(is
): string Option
=
56 implode(takewhile(not
o isSpace
)
57 (dropwhile
isSpace (readLn is
)))