Loading ...
Sorry, an error occurred while loading the content.

9309Re: "ocaml_beginners"::[] getting rid of a global variable

Expand Messages
  • Richard Jones
    Feb 2, 2008
    • 0 Attachment
      On Sat, Feb 02, 2008 at 06:42:26PM +0530, Martin DeMello wrote:
      > I'm writing a wordsearch program that reads a dictionary file into a
      > global array:
      >
      > (*--------------------------------------------------------------------------------------------------*)
      >
      > open Bigarray
      > open Printf
      >
      > let dawg =
      > let fd = Unix.openfile "csw.dwg" [ Unix.O_RDONLY ] 0 in
      > Array1.map_file fd int32 c_layout false (-1);;
      >
      > (* bitfield accessors *)
      > let w_pos = Int32.shift_left Int32.one 23;;
      > let n_pos = Int32.shift_left Int32.one 22;;
      > let ptr_mask = Int32.of_string "0b0000000000011111111111111111111";;
      > let start_node = 1;;
      >
      > let _letter node = Char.chr(Int32.to_int(Int32.shift_right_logical node 24));;
      > let _wordp node = (Int32.logand node w_pos) <> Int32.zero;;
      > let _lastp node = (Int32.logand node n_pos) <> Int32.zero;;
      > let _ptr node = Int32.to_int (Int32.logand node ptr_mask);;
      >
      > (* access nodes via their dawg index *)
      > let lastp ix = _lastp dawg.{ix};;
      > let wordp ix = _wordp dawg.{ix};;
      > let letter ix = _letter dawg.{ix};;
      > let ptr ix = _ptr dawg.{ix};;
      >
      > (*--------------------------------------------------------------------------------------------------*)
      >
      > and thereafter uses the lastp, wordp, letter and ptr functions as the
      > public interface for the rest of the code. This saves me having to
      > pass the dawg as a parameter to every function in the program, but is
      > getting in the way of refactoring the program now, and makes the code
      > feel unmaintainable. My instinctive reaction is to wrap the dawg and
      > its accessors into a class, but from what I've gathered, most OCaml
      > programmers don't really use classes, especially for speed-critical
      > code. What's the best way to go about doing this?

      I'm not quite sure where your pain point is, but if I'm understanding
      this you want to hide the _symbols? As you said, avoid classes.
      Instead, use nesting:

      let lastp, wordp, letter, ptr =
      (* All the above code, indented by 2 spaces, with ';;' replaced by 'in' *)
      lastp, wordp, letter, ptr ;;

      Then the following code has access to only lastp, wordp, letter and
      ptr, and no access to the other symbols.

      If I've missed the point please let me know.

      Rich.

      --
      Richard Jones
      Red Hat
    • Show all 12 messages in this topic