Skip to content

Commit d035bae

Browse files
committed
Std: Add an generator for 'option' datatype
1 parent 3f04175 commit d035bae

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib_bam/std.ml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,10 @@ let oneofg : ?shrinker:int Shrinker.t -> 'a Gen.t list -> 'a Gen.t =
284284

285285
let oneofl : ?shrinker:int Shrinker.t -> 'a list -> 'a Gen.t =
286286
fun ?shrinker list -> oneofg ?shrinker (List.map Gen.return list)
287+
288+
let option ?shrinker ?(none_weight = 1) ?(some_weight = 1) gen =
289+
oneof ?shrinker
290+
[ (none_weight, return None)
291+
; ( some_weight
292+
, let* value = gen in
293+
return (Some value) ) ]

lib_bam/std.mli

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,24 @@ val oneofl : ?shrinker:int Shrinker.t -> 'a list -> 'a t
230230
(** [oneofl ?shrinker list] is an alias for
231231
[oneofg ?shrinker (List.map Gen.return list] *)
232232

233+
val option :
234+
?shrinker:int Shrinker.t
235+
-> ?none_weight:int
236+
-> ?some_weight:int
237+
-> 'a t
238+
-> 'a option t
239+
(** [option ?choice_shrinker ?none_weight ?some_weight gen] builds a generator
240+
of type ['a option t] that produces
241+
242+
- [None] with “relative” weight [none_weight]
243+
- [Some x] with “relative” weight [some_weight], where [x] ← [gen]
244+
245+
Both [none_weight] and [some_weight] default to [1]. Internally,
246+
this is just a two‑case [oneof] (index 0 = None, 1 = Some); the
247+
[choice_shrinker] (default [Shrinker.Int 0]) will therefore always
248+
try to shrink towards [None] first.
249+
*)
250+
233251
module Syntax : sig
234252
val return : 'a -> 'a t
235253
(** Syntactic sugar {!return} *)

0 commit comments

Comments
 (0)