Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Doing the transition from imperative to functional (and some other Q)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Yamagata Yoriyuki <yoriyuki@m...>
Subject: Re: [Caml-list] Doing the transition from imperative to functional (and some other Q)
From: "Christian Schaller" <Christian.Schaller@siemens.com>
Subject: [Caml-list] Doing the transition from imperative to functional (and some other Q)
Date: Wed, 4 Feb 2004 17:09:30 +0100

> After I decided that there has to be a functional way for this, too,
> (hate typing all those ! and := )I came up with the following version:

Using (tail) recursion is the way.  Here is a code for 31-bits CRC.
(Not exactly same to yours, but it would give you an idea.)

(* CRC-hash, algorithm comes from addnode.c/pathalias *)
(* 31-bits CRC-polynomial, by Andrew Appel*)
let poly = 0x48000000

let crc_tbl = Array.init 128 (fun i ->
  let rec loop j sum =
    if j < 0 then sum else
    if i land (1 lsl j) <> 0 then
      loop (j - 1) (sum lxor (poly lsr j))
    else
      loop (j - 1) sum in
  loop (7 - 1) 0)

let string_hash v =
  let rec loop i sum =
    if i < 0 then sum else
    let a = Char.code v.[i] in
    let sum = sum lsr 7 lxor crc_tbl.(sum lxor a land 0x7f) in
    loop (i - 1) sum in
  loop (String.length v - 1) 0

> Though I am a strong believer in static typing, above versions
> disappoint me heavily because of type restrictions.  Is there any way to
> write above version on arbitrary sequences like Arrays, Lists,
> Strings?

You could use Functor, but it would be too heavy weight.
 
> Actually, I would have preferred the buffer data type because I can use
> that one for fast reading of a file.  However, I cannot fold over a
> buffer :(

You don't need to load the whole file.  Read the file one character by
one, and updates the sum.

--
Yamagata Yoriyuki

-------------------
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