Version française
Home     About     Download     Resources     Contact us    
Browse thread
Fwd: Re: [Caml-list] The boon of static type checking
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Eric C. Cooper <ecc@c...>
Subject: Re: [Caml-list] String to list to string
On Tue, Feb 15, 2005 at 10:33:16AM +0000, Richard Jones wrote:
> If you can suggest suitable fold_left and fold_right functions, then
> they can be added to ExtLib.

Here's what I use:

val string_fold_left : ('a -> char -> 'a) -> 'a -> string -> 'a
val string_fold_right : (char -> 'a -> 'a) -> 'a -> string -> 'a

let string_fold_left f init str =
  let n = String.length str in
  let rec loop i result =
    if i = n then result
    else loop (i + 1) (f result str.[i])
  in
  loop 0 init

let string_fold_right f init str =
  let n = String.length str in
  let rec loop i result =
    if i = 0 then result
    else
      let i' = i - 1 in
      loop i' (f str.[i'] result)
  in
  loop n init

-- 
Eric C. Cooper          e c c @ c m u . e d u