| 1 |
datatype 'a Option = None | Some of 'a |
| 2 |
|
| 3 |
fun digit n = chr(ord #"0" + n) |
| 4 |
fun digits(n,acc) = |
| 5 |
if n >=0 andalso n<=9 then digit n:: acc |
| 6 |
else digits (n div 10, digit(n mod 10) :: acc) |
| 7 |
|
| 8 |
fun toString(n) = implode(digits(n,[])) |
| 9 |
|
| 10 |
fun writeln s = print(s^"\n") |
| 11 |
|
| 12 |
fun percent(i: int, j: int)(*:int*) = |
| 13 |
floor((real i * 100.0)/real j) |
| 14 |
|
| 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. |
| 20 |
*) |
| 21 |
exception Impossible |
| 22 |
fun seek (pred: char -> bool) (is: TextIO.instream): char list = |
| 23 |
let fun readLoop() = |
| 24 |
(case explode (TextIO.inputN(is, 1)) of |
| 25 |
[] => [] |
| 26 |
| [char] => char :: (if pred char then [] |
| 27 |
else readLoop()) |
| 28 |
| _ => (print "lib.seek: impossible"; raise Impossible)) |
| 29 |
in readLoop() |
| 30 |
end |
| 31 |
|
| 32 |
fun readLn(is) = seek(fn ch => ch = #"\n")is |
| 33 |
|
| 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 |
| 39 |
in drop_loop l |
| 40 |
end |
| 41 |
|
| 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 [] |
| 47 |
in take_loop l |
| 48 |
end |
| 49 |
|
| 50 |
fun isSpace(ch:char) = |
| 51 |
ch = #" " orelse ch = #"\t" orelse ch = #"\n" |
| 52 |
(* orelse ch= "\f" orelse ch = "\r" orelse ch = "\v"*) |
| 53 |
|
| 54 |
fun readWord(is): string Option = |
| 55 |
case |
| 56 |
implode(takewhile(not o isSpace) |
| 57 |
(dropwhile isSpace (readLn is))) |
| 58 |
of "" => None |
| 59 |
| word => Some word |
| 60 |
|
| 61 |
|