Compare commits

..

3 commits

Author SHA1 Message Date
Fardale
3ec3474514
Merge 273ba69ea3 into 4613aafb30 2025-02-09 09:26:57 +08:00
Simon Cruanes
4613aafb30
feat: add CCFun.with_return
Some checks failed
Build and Test / build (push) Has been cancelled
Build and Test / format (push) Has been cancelled
2025-02-07 16:57:56 -05:00
Adlertz, Niclas
4294dc7ca3 Add square brackets in comment for CCList.return
Some checks failed
Build and Test / build (push) Has been cancelled
Build and Test / format (push) Has been cancelled
2025-01-28 22:19:11 -05:00
4 changed files with 36 additions and 1 deletions

View file

@ -67,6 +67,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 ( %> ) f g = compose g f let ( %> ) f g = compose g f

View file

@ -83,6 +83,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. *)

View file

@ -375,7 +375,7 @@ val mguard : bool -> unit t
@since 3.1 *) @since 3.1 *)
val return : 'a -> 'a t val return : 'a -> 'a t
(** [return x] is [x]. *) (** [return x] is [[x]]. *)
val take : int -> 'a t -> 'a t val take : int -> 'a t -> 'a t
(** [take n l] takes the [n] first elements of the list [l], drop the rest. *) (** [take n l] takes the [n] first elements of the list [l], drop the rest. *)

View file

@ -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"