summaryrefslogtreecommitdiff
path: root/Source/Jennisys/Utils.fs
blob: 56b6b7794bf8d171fe437512891abe3fb665ca38 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
//  ####################################################################
///   Various utility functions
///
///   author: Aleksandar Milicevic (t-alekm@microsoft.com)
//  ####################################################################

module Utils

// -------------------------------------------
// ----------- collection util funcs ---------
// -------------------------------------------

//  =====================================
/// ensures: ret = b ? Some(b) : None
//  =====================================
let BoolToOption b =
  if b then
    Some(b)
  else
    None

//  =====================================
/// ensures: ret = (opt == Some(_))
//  =====================================
let OptionToBool opt = 
  match opt with
  | Some(_) -> true
  | None -> false

//  =====================================
/// ensures: ret = (opt == Some(_))
//  =====================================
let IsSomeOption opt = 
  match opt with
  | Some(_) -> true
  | None -> false

//  =====================================
/// ensures: ret = (opt == None)
//  =====================================
let IsNoneOption opt = IsSomeOption opt |> not

//  =====================================
/// requres: x = Some(a) or failswith msg
/// ensures: ret = a
//  =====================================
let ExtractOptionMsg msg x = 
  match x with
  | Some(a) -> a
  | None -> failwith msg

//  ====================
/// requres: x = Some(a)
/// ensures: ret = a
//  ====================
let ExtractOption x = 
  ExtractOptionMsg "can't extract anything from a None" x

//  ====================================
/// ensures: res = Some(a) ==> ret = a
/// ensures: res = None ==> ret = defVal
//  ====================================
let ExtractOptionOr defVal opt = 
  match opt with 
  | Some(a) -> a
  | None -> defVal

//  ==========================================================
/// requres: List.length lst <= 1, otherwise fails with errMsg
/// ensures: if |lst| = 0 then
///            ret = None
///          else
///            ret = Some(lst[0])
//  ==========================================================
let ListToOptionMsg  lst errMsg = 
  if List.length lst > 1 then
    failwith errMsg
  if List.isEmpty lst then
    None
  else
    Some(lst.[0])

let ListToOption lst = ListToOptionMsg lst "given list contains more than one element"

let ListDeduplicate lst = 
  let rec __Dedup lst (visitedSet: System.Collections.Generic.HashSet<_>) acc = 
    match lst with
    | fs :: rest ->  
        let newAcc = 
          if visitedSet.Add(fs) then
            acc @ [fs]
          else
            acc
        __Dedup rest visitedSet newAcc
    | _ -> acc
  __Dedup lst (new System.Collections.Generic.HashSet<_>()) []

let rec ListCombine combinerFunc lst1 lst2 = 
  match lst1 with
  | e1 :: rest ->
      let resLst1 = lst2 |> List.fold (fun acc e2 -> acc @ [combinerFunc e1 e2]) []
      List.concat [resLst1; ListCombine combinerFunc rest lst2]
  | [] -> []

let rec ListCombineMult combinerFunc lst1 lst2 = 
  match lst1 with
  | e1 :: rest ->
      let resLst1 = lst2 |> List.fold (fun acc e2 -> acc @ combinerFunc e1 e2) []
      List.concat [resLst1; ListCombineMult combinerFunc rest lst2]
  | [] -> []
        
//  =============================================================
/// ensures: forall i :: 0 <= i < |lst| ==> ret[i] = Some(lst[i])
//  =============================================================
let rec ConvertToOptionList lst = 
  match lst with
  | fs :: rest -> Some(fs) :: ConvertToOptionList rest
  | [] -> []

//  =========================================================
/// requres: Seq.length seq <= 1, otherwise fails with errMsg
/// ensures: if |seq| = 0 then
///            ret = None
///          else
///            ret = Some(seq[0])
//  =========================================================
let SeqToOptionMsg seq errMsg = 
  if Seq.length seq > 1 then
    failwith errMsg
  if Seq.isEmpty seq then
    None
  else
    Some(Seq.nth 0 seq)

let SeqToOption seq = SeqToOptionMsg seq "given seq contains more than one element"

//  =========================================================
/// requires: Set.count set <= 1, otherwise fails with errMsg
/// ensures: if |set| = 0 then
///            ret = None
///          else
///            ret = Some(set[0])
//  =========================================================
let SetToOptionMsg set errMsg = 
  if Set.count set > 1 then
    failwith errMsg
  if (Set.isEmpty set) then
    None
  else 
    Some(set |> Set.toList |> List.head)

let SetToOption set = SetToOptionMsg set "give set contains more than one value"

//  ============================================================
/// requires: n >= 0
/// ensures:  |ret| = n && forall i :: 0 <= i < n ==> ret[i] = e
//  ============================================================
let rec GenList n e =
  if n < 0 then 
    failwith "n must be positive"
  if n = 0 then
    []
  else
    e :: (GenList (n-1) e)

//  =======================================
/// ensures: forall i :: 0 <= i < |lst| ==> 
///            if lst[i] = oldElem then
///              ret[i] = newElem
///            else
///              ret[i] = lst[i]
//  =======================================
let ListReplace oldElem newElem lst = 
  lst |> List.map (fun e -> if e = oldElem then newElem else e)

//  =================================================
/// if (exists (k,v) :: (k,v) in lst && k = key) then
///   ret = Some(v)
/// else
///   ret = None
//  =================================================
let ListMapTryFind key lst = 
  let filtered = lst |> List.filter (fun (k,v) -> k = key)
  match filtered with
  | fs :: rest -> Some(snd fs)
  | [] -> None

//  ==================================================
/// Replaces the first occurence of the given key in 
/// the given list with the given value, or appends 
/// (key,value) if key does not exist in the list
//  ==================================================
let rec ListMapAdd key value lst = 
  match lst with
  | (k,v) :: rest -> if k = key then (k, value) :: rest else (k,v) :: (ListMapAdd key value rest)
  | [] -> [(key,value)]                                           

//  ==========================
/// ensures: ret = elem in lst
//  ==========================
let ListContains elem lst = 
  lst |> List.exists (fun e -> e = elem)

//  ====================================================
/// Removes all elements in lst that are equal to "elem"
//  ====================================================
let ListRemove elem lst = 
  lst |> List.choose (fun e -> if e = elem then None else Some(e))

let rec ListRemoveIdx idx lst = 
  if idx = 0 then
    List.tail lst
  else 
    List.head lst :: ListRemoveIdx (idx - 1) (List.tail lst)  

//  ===============================================================
/// ensures: |ret| = max(|lst| - cnt, 0)
/// ensures: forall i :: cnt <= i < |lst| ==> ret[i] = lst[i-cnt]
//  ===============================================================
let rec ListSkip cnt lst = 
  if cnt = 0 then
    lst    
  else
    match lst with
    | fs :: rest -> ListSkip (cnt-1) rest
    | [] -> []

//  ===============================================================
/// ensures: forall i :: 0 <= i < max(|srcList|, |dstList|) ==> 
///            if i = idx then
///              ret[i] = v
///            elif i < |srcList| then
///              ret[i] = srcList[i]
///            else
///              ret[i] = dstList[i] 
//  ===============================================================
let rec ListBuild srcList idx v dstList =
  match srcList, dstList with
  | fs1 :: rest1, fs2 :: rest2 -> if idx = 0 then
                                    v :: List.concat [rest1 ; ListSkip (List.length rest1) rest2]
                                  else 
                                    fs1 :: ListBuild rest1 (idx-1) v rest2
  | [],           fs2 :: rest2 -> if idx = 0 then
                                    v :: rest2
                                  else 
                                    fs2 :: ListBuild [] (idx-1) v rest2
  | _,            []           -> failwith "index out of range"

//  =======================================
/// ensures: forall i :: 0 <= i < |lst| ==>
///            if i = idx then
///              ret[i] = v
///            else
///              ret[i] = lst[i]
//  =======================================
let rec ListSet idx v lst =
  match lst with
  | fs :: rest -> if idx = 0 then 
                    v :: rest
                  else
                    fs :: ListSet (idx-1) v rest
  | [] -> failwith "index out of range"

exception KeyAlreadyExists

//  =======================================
/// requires (key |--> value) !in map
///
/// ensures ret = map ++ (key |--> value)
//  =======================================
let MapAddNew key value map = 
  match Map.tryFind key map with
  | Some(existingValue) -> 
      if existingValue = value then
        map
      else 
        raise KeyAlreadyExists
  | None -> 
      map |> Map.add key value

//  =======================================
/// ensures: forall k,v :: 
///            if k,v in map2 then
//               k,v in ret
///            elif k,v in map1 then
///              k,v in ret
///            else
///              k,v !in ret
//  =======================================
let rec MapAddAll map1 map2 = 
  map2 |> Map.fold (fun acc k v -> acc |> Map.add k v) map1

//  =======================================
/// ensures: |ret| = 1
/// ensures: (key -> value) in ret
//  =======================================
let MapSingleton key value = 
  Map.empty |> Map.add key value

let MapKeys map = 
  map |> Map.toList |> List.map (fun (k,v) -> k)

let MapReplaceKey oldKey newKey newVal map = 
  map |> Map.toList |> List.fold (fun acc (k,v) -> if k = oldKey then acc |> Map.add newKey newVal else acc |> Map.add k v) Map.empty

// -------------------------------------------
// ------------ algorithms -------------------
// -------------------------------------------

//  =======================================================================
/// Topologically sorts a given list
///
/// ensures: |ret| = |lst|
/// ensures: forall e in lst :: e in ret
/// ensures: forall i,j :: 0 <= i < j < ==> not (followsFunc ret[j] ret[i])
//  =======================================================================
let rec TopSort followsFunc lst = 
  match lst with
  | [] -> []
  | fs :: [] -> [fs]
  | fs :: rest -> 
      let min = rest |> List.fold (fun acc elem -> if followsFunc acc elem then elem else acc) fs
      min :: TopSort followsFunc (ListRemove min lst)
                                                 
// -------------------------------------------
// ------ string active patterns -------------
// -------------------------------------------

let (|Prefix|_|) (p:string) (s:string) =
  if s.StartsWith(p) then
    Some(s.Substring(p.Length))
  else
    None
                 
// -------------------------------------------
// --------------- workflow ------------------
// -------------------------------------------

let IfDo1 cond func1 a =
  if cond then
    func1 a
  else 
    a

let IfDo2 cond func2 (a1,a2) =
  if cond then
    func2 a1 a2
  else
    a1,a2 

let Ite cond f1 f2 =
  if cond then
    f1
  else
    f2

type CascadingBuilder<'a>(failVal: 'a) = 
  member this.Bind(v, f) =
    match v with
    | Some(x) -> f x
    | None -> failVal
  member this.Return(v) = v

// -------------------------------------------
// --------------- random --------------------
// -------------------------------------------

let Iden x = x