mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-06 03:05:28 -05:00
feat: add CCFun.with_return
This commit is contained in:
parent
4294dc7ca3
commit
4613aafb30
3 changed files with 35 additions and 0 deletions
|
|
@ -61,6 +61,13 @@ let rec iterate n f x =
|
||||||
else
|
else
|
||||||
iterate (n - 1) f (f x)
|
iterate (n - 1) f (f x)
|
||||||
|
|
||||||
|
let[@inline] with_return (type ret) f : ret =
|
||||||
|
let exception E of ret in
|
||||||
|
let return x = raise_notrace (E x) in
|
||||||
|
match f return with
|
||||||
|
| res -> res
|
||||||
|
| exception E res -> res
|
||||||
|
|
||||||
module Infix = struct
|
module Infix = struct
|
||||||
(* default implem for some operators *)
|
(* default implem for some operators *)
|
||||||
let ( %> ) = compose
|
let ( %> ) = compose
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,22 @@ val iterate : int -> ('a -> 'a) -> 'a -> 'a
|
||||||
[x], [iterate 1 f x] is [f x], [iterate 2 f x] is [f (f x)], etc.
|
[x], [iterate 1 f x] is [f x], [iterate 2 f x] is [f (f x)], etc.
|
||||||
@since 2.1 *)
|
@since 2.1 *)
|
||||||
|
|
||||||
|
val with_return : (('ret -> 'a) -> 'ret) -> 'ret
|
||||||
|
(** [with_return f] is [f return], where [return] is a function
|
||||||
|
that can be invoked to exit the scope early.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
{[
|
||||||
|
let find_array arr x =
|
||||||
|
let@ return = with_return in
|
||||||
|
for i = 0 to Array.length arr-1 do
|
||||||
|
if arr.(i) = x then return i;
|
||||||
|
done;
|
||||||
|
-1
|
||||||
|
]}
|
||||||
|
|
||||||
|
@since NEXT_RELEASE *)
|
||||||
|
|
||||||
(** {2 Infix}
|
(** {2 Infix}
|
||||||
|
|
||||||
Infix operators. *)
|
Infix operators. *)
|
||||||
|
|
|
||||||
|
|
@ -21,3 +21,15 @@ true
|
||||||
t @@ fun () -> CCFun.((succ %> string_of_int) 2 = "3");;
|
t @@ fun () -> CCFun.((succ %> string_of_int) 2 = "3");;
|
||||||
t @@ fun () -> CCFun.((( * ) 3 % succ) 5 = 18);;
|
t @@ fun () -> CCFun.((( * ) 3 % succ) 5 = 18);;
|
||||||
t @@ fun () -> CCFun.(succ @@ ( * ) 2 @@ pred @@ 3 = 5)
|
t @@ fun () -> CCFun.(succ @@ ( * ) 2 @@ pred @@ 3 = 5)
|
||||||
|
|
||||||
|
let find_array arr x =
|
||||||
|
let@ return = with_return in
|
||||||
|
for i = 0 to Array.length arr - 1 do
|
||||||
|
if arr.(i) = x then return i
|
||||||
|
done;
|
||||||
|
-1
|
||||||
|
;;
|
||||||
|
|
||||||
|
eq 1 @@ find_array [| "a"; "b"; "c" |] "b";;
|
||||||
|
eq 2 @@ find_array [| "a"; "b"; "c" |] "c";;
|
||||||
|
eq (-1) @@ find_array [| "a"; "b"; "c" |] "hello"
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue