summaryrefslogtreecommitdiff
path: root/Jennisys/Utils.fs
blob: 8a2e107ee719fb9e24b071d92cfd71d27cf127fb (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
module Utils

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

let ListToOption lst = 
  assert (List.length lst <= 1)
  if List.isEmpty lst then
    None
  else
    Some(lst.[0])

let SeqToOption seq = 
  assert (Seq.length seq <= 1)
  if Seq.isEmpty seq then
    None
  else
    Some(Seq.nth 0 seq)

let rec GenList n =
  if n = 0 then
    []
  else
    None :: (GenList (n-1))

let rec ListSkip cnt lst = 
  if cnt = 0 then
    lst
  else
    match lst with
    | fs :: rest -> ListSkip (cnt-1) rest
    | [] -> []

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"


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"

// -------------------------------------------
// ------ string active patterns -------------
// -------------------------------------------

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

let (|Exact|_|) (p:string) (s:string) =
  if s = p then
    Some(s)
  else
    None