-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.sml
66 lines (64 loc) · 1.69 KB
/
helpers.sml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
structure Helpers =
struct
(*
readLines path
TYPE: string -> string list
PRE: path must be the path of an existing (readable) file.
POST: a list of lines that compromise the file at path.
*)
fun readLines path =
let
(*
readLines' s
TYPE: TextIO.instream -> string list
PRE: s is an open instream.
POST: a list of all lines read from s until its empty.
*)
fun readLines' s =
case TextIO.inputLine s of
NONE => (TextIO.closeIn s; [])
| SOME(line) => line::readLines' s
in
readLines' (TextIO.openIn path)
end;
(*
getIntList s
TYPE: string -> int list
PRE: true
POST: a list of integers based on the comma separated numbers in s.
EXAMPLE: getIntList "1,2,3" = [1,2,3]
getIntList "10,foo,20" = [10,20]
*)
fun getIntList s =
let
(*
getInt s
TYPE: substring -> int option
PRE: true
POST: the integer representation of s if valid, or NONE otherwise.
EXAMPLE: getInt (Substring.full("1")) = SOME 1
getInt (Substring.full("foo")) = NONE
*)
fun getInt s = Int.fromString(Substring.string(s))
(*
split (s, c)
TYPE: string * char -> substring list
PRE: true
POST: s split into all substrings separated by c.
EXAMPLE: split ("foo,bar", #","); val it = ["foo", "bar"]: substring list
*)
fun split (s, c) = Substring.fields (fn x => x = c) (Substring.full s)
in
List.mapPartial getInt (split (s, #","))
end;
(*
contains (l, x)
TYPE: 'a list * 'a -> bool
PRE: true
POST: true if the list l contains x and false otherwise.
EXAMPLE: contains ([1,2,3], 3) = true
contains ([1,2,3], 4) = false
*)
fun contains (l, x) =
List.exists (fn v => v = x) l;
end;