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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Julian Assange <proff@i...>
Subject: addressable_to_list

The following ocaml function converts a string to a list:
(which btw, I guess should be in the String module)

let string_to_list s =
  let len = String.length s in
  let rec scan n =
    if n < len then
      s.[n] :: scan (n + 1)
    else
      []
  in
    scan len

However, what I'd like to be able to do this for any countable thing.

e.g

let nthable_to_list s fnth flen =
  let len = flen s in
  let rec scan n =
    if n < len then
      fnth s n :: scan (n + 1)
    else
      []
  in
    scan len

Then one can of course simulate the first code snippit with:

let string_of_list s = nthable_to_list s (fun s n -> s.[n]) (fun s -> String.length s)

I know how this is done in Haskell, but how do something like it in O'caml?

A couple of useful string functions that are missing:

        conversion, strings <-> bigarrays of chars a bigarry like
        create function, which takes a function argument. (regular
        Array's also have the same problem). String has functions to
        create an empty, constant filled string, or an uninitialised
        string. This is pretty important, because Digest for instance,
        only takes strings.

        While I'm on the subject of array initialisers, the
        new safe array creation could be improved. From memory,
        it takes a function which takes an int and 
        returns an initialisation element. It would be better
        if the counting was left upto the user supplied function
        and the output was fed back into the input. e.g like foldr.
        e.g

               ('a -> 'b * 'a) -> 'b array

        1.. initialisation would then look like

                (fun x -> x, x+1)


Cheers,
Julian.