This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] queasiness about Exit
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2001-11-15 (21:43) From: Marcin 'Qrczak' Kowalczyk Subject: Re: [Caml-list] queasiness about Exit
```Thu, 15 Nov 2001 17:58:32 +0100, Andreas Rossberg <rossberg@ps.uni-sb.de> pisze:

> It is not too difficult to provide variations of iter and folds for
> your data structures that allow early breaks. For example, consider:
>
> 	iter' : ('a -> bool) -> 'a array -> unit
>
> Unlike the standard version of iter, the argument function returns a
> boolean saying whether iteration should continue. Similarly for folds:
>
> 	fold_left' : ('a -> 'b -> 'a * bool) -> 'a -> 'b array -> 'a

An alternative is

fold_right' : ('a -> (unit -> 'b) -> 'b) -> 'a array -> (unit -> 'b) -> 'b

which can also replace iter (with 'b = unit).

When fold in either direction could be used, fold_left is usually
beter if the folding function is strict, and fold_right if it's lazy.

> let exists p = fold_left' (fun b x -> let b' = b || p x in (b', not b')) true

let exists p xs = fold_right' (fun x bf -> p x || bf ()) xs (fun () -> false)

Wrapping "init" (shouldn't it be called "last" here?) in a closure is
unnecessary for this case but it's important e.g. for concatenation
of lazy lists.

--
__("<  Marcin Kowalczyk * qrczak@knm.org.pl http://qrczak.ids.net.pl/
\__/
^^
QRCZAK

-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr

```