<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE message PUBLIC
  "-//MLarc//DTD MLarc output files//EN"
  "../../mlarc.dtd"[
  <!ATTLIST message
    listname CDATA #REQUIRED
    title CDATA #REQUIRED
  >
]>

  <?xml-stylesheet href="../../mlarc.xsl" type="text/xsl"?>


<message 
  url="2002/12/aea498f4b382c4c38c55ec6bcfe788a7"
  from="Jeremy Fincher &lt;tweedgeezer@h...&gt;"
  author="Jeremy Fincher"
  date="2002-12-06T19:58:20"
  subject="[Caml-list] function"
  prev="2002/12/972f008787fd15d53574078e2a8b709b"
  next="2002/12/4555ce883e1f38c5fb439263eaeb6d6b"
  prev-thread="2002/12/5601889e766f585d4843a475bbbf5315"
  next-thread="2002/12/4555ce883e1f38c5fb439263eaeb6d6b"
  root="../../"
  period="month"
  listname="caml-list"
  title="Archives of the Caml mailing list">

<thread subject="[Caml-list] function">
<msg 
  url="2002/12/aea498f4b382c4c38c55ec6bcfe788a7"
  from="Jeremy Fincher &lt;tweedgeezer@h...&gt;"
  author="Jeremy Fincher"
  date="2002-12-06T19:58:20"
  subject="[Caml-list] function">
</msg>
</thread>

<contents>
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 &lt; 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 -&gt; c :: acc) []
(* End "Why in the world?" comment *)

let digitToInt c =
  match c with
    | '0' -&gt; 0
    | '1' -&gt; 1
    | '2' -&gt; 2
    | '3' -&gt; 3
    | '4' -&gt; 4
    | '5' -&gt; 5
    | '6' -&gt; 6
    | '7' -&gt; 7
    | '8' -&gt; 8
    | '9' -&gt; 9
    | _   -&gt; 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 -&gt; string_foldr (fun c l2 -&gt; 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

</contents>

</message>

