summaryrefslogtreecommitdiffstats
path: root/lib/prelude.ml
blob: f571a4d0b55a2768c1e32302a517ded76f61427f (about) (plain) (blame)
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
include Core
module Time_ns = Time_ns_unix

module List = struct
  include List

  let map_result ~(f : 'a -> ('b, 'c) result) : 'a list -> ('b list, 'c) result
      =
    let open Result.Let_syntax in
    let rec go = function
      | [] -> return []
      | x :: xs ->
          let%map x' = f x and xs' = go xs in
          x' :: xs'
    in
    go
end

module Map = struct
  include Map

  let fold_result (m : ('k, 'v, _) t) ~(init : 'acc)
      ~(f : key:'k -> data:'v -> 'acc -> ('acc, 'err) result) :
      ('acc, 'err) result =
    fold_until m ~init
      ~f:(fun ~key ~data acc ->
        match f ~key ~data acc with
        | Ok acc' -> Continue acc'
        | Error _ as res -> Stop res)
      ~finish:(fun v -> Ok v)

  let fold_option (m : ('k, 'v, _) t) ~(init : 'acc)
      ~(f : key:'k -> data:'v -> 'acc -> 'acc option) : 'acc option =
    fold_until m ~init
      ~f:(fun ~key ~data acc ->
        match f ~key ~data acc with
        | Some acc' -> Continue acc'
        | None -> Stop None)
      ~finish:(fun v -> Some v)
end

module Z = struct
  include Z

  let sexp_of_t x = Sexp.Atom (Z.to_string x)
end

module Result = struct
  include Result

  let unwrap = function
    | Error _ -> failwith "Result.unwrap: unexpected (Error _)"
    | Ok v -> v
end