Backport from sid to buster
[hcoop/debian/mlton.git] / regression / lib.sml
CommitLineData
7f918cf1
CE
1datatype 'a Option = None | Some of 'a
2
3fun digit n = chr(ord #"0" + n)
4fun 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
8fun toString(n) = implode(digits(n,[]))
9
10fun writeln s = print(s^"\n")
11
12fun 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*)
21exception Impossible
22fun 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
32fun readLn(is) = seek(fn ch => ch = #"\n")is
33
34(* dropwhile: ('a -> bool) -> 'a list -> 'a list; endomorphic *)
35fun 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 *)
43fun 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
50fun isSpace(ch:char) =
51 ch = #" " orelse ch = #"\t" orelse ch = #"\n"
52 (* orelse ch= "\f" orelse ch = "\r" orelse ch = "\v"*)
53
54fun 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