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

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

Expand Messages
  • Peng Zang
    Feb 4, 2008
    • 0 Attachment
      Hash: SHA1

      On Saturday 02 February 2008 08:12:26 am Martin DeMello wrote:
      > 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?
      > martin

      Just would like to point out there's nothing wrong with using classes. One of
      the best points of OCaml in my opinion is the ability to express your code
      the way it best suites you. As to speed, someone one on this list (can't
      recall who just now) mentioned that objects can be quite fast. Method class
      for example, are cached (although I don't think they can be inlined so you'll
      always incur a function application cost -- but that's pretty low).

      So if you think classes work well here (eg. if you may have multiple
      dictionaries open at once and so a global variable would be bad), a classes
      approach like this is fine:

      (* 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 *)
      class wordsearcher dictfilename = object
      val dawg = Array1.map_file (Unix.openfile dictfilename [ Unix.O_RDONLY ] 0)
      int32 c_layout false (-1)
      method lastp ix = _lastp dawg.{ix}
      method wordp ix = _wordp dawg.{ix}
      method letter ix = _letter dawg.{ix}
      method ptr ix = _ptr dawg.{ix}
      -----BEGIN PGP SIGNATURE-----
      Version: GnuPG v2.0.7 (GNU/Linux)

      -----END PGP SIGNATURE-----
    • Show all 12 messages in this topic