Merge pull request #187 from emillon/ccfun-iterate

Add `CCFun.iterate`
This commit is contained in:
Simon Cruanes 2018-02-14 08:40:42 -06:00 committed by GitHub
commit dd24feab60
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 0 deletions

View file

@ -27,3 +27,4 @@
- Orbifx (Stavros Polymenis)
- Rand (@rand00)
- Dave Aitken (@actionshrimp)
- Etienne Millon (@emillon)

View file

@ -66,6 +66,26 @@ let finally2 ~h f x y =
ignore (h ());
raise e
let rec iterate n f x =
if n < 0 then
invalid_arg "CCFun.iterate"
else if n = 0 then
x
else
iterate (n - 1) f (f x)
(*$= iterate & ~printer:Q.Print.int
10 (iterate 0 succ 10)
11 (iterate 1 succ 10)
12 (iterate 2 succ 10)
15 (iterate 5 succ 10)
*)
(*$R
assert_raises
(Invalid_argument "CCFun.iterate")
(fun () -> iterate (-1) succ 10)
*)
module Monad(X : sig type t end) = struct
type 'a t = X.t -> 'a
let return x _ = x

View file

@ -76,6 +76,11 @@ val opaque_identity : 'a -> 'a
in OCaml >= 4.03).
@since 0.18 *)
val iterate : int -> ('a -> 'a) -> 'a -> 'a
(** [iterate n f] is [f] iterated [n] times. That is to say, [iterate 0 f x] is
[x], [iterate 1 f x] is [f x], [iterate 2 f x] is [f (f x)], etc.
@since NEXT_RELEASE *)
(** {2 Monad}
Functions with a fixed domain are monads in their codomain. *)