Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jeremy Fincher <tweedgeezer@h...>
Subject: [Caml-list] function
I prefer this:

(* Why in the world aren't these included in the standard library? *)
let string_foldr f init s =
  let rec aux i x =
    if i < 0 then
       x
    else
       aux (i-1) (f (String.get s i) x)
  in
    aux (String.length s - 1) init

let explode = string_foldr (fun c acc -> c :: acc) []
(* End "Why in the world?" comment *)

let digitToInt c =
  match c with
    | '0' -> 0
    | '1' -> 1
    | '2' -> 2
    | '3' -> 3
    | '4' -> 4
    | '5' -> 5
    | '6' -> 6
    | '7' -> 7
    | '8' -> 8
    | '9' -> 9
    | _   -> failwith "invalid digit"

let f l = List.map digitToInt (List.flatten (List.map explode l))

(* Or, to be more efficient, without constructing the intermediate lists via 
explode. *)
let f' l = List.fold_right (fun s l1 -> string_foldr (fun c l2 -> digitToInt 
c :: l2) l1 s) l []
(* Out of curiosity, why does fold_right take the initial value after the 
list it operates on? *)

I don't think users would be as tempted to write imperative, possibly 
inefficient code working with strings if the String module included better 
iterators such a fold_right and fold_left (and maybe even map, since strings 
are mutable in O'Caml and it could thus be done efficiently).

Jeremy

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners