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

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

Expand Messages
  • yami_no_shoryuu
    Feb 6, 2008
    • 0 Attachment
      I would propose a functor-based code which does pretty much the same :)
      like Jon has suggested in http://tech.groups.yahoo.com/group/ocaml_beginners/
      message/9311

      (* code starts *)
      module Ops_fd(S: sig val fd: Unix.file_descr end) = struct
      open Bigarray
      open Printf

      let dawg = Array1.map_file S.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 };;

      (* Close operation *)
      let close () =
      Unix.close S.fd
      ;;

      end

      module Ops(S: sig val filename: string end) = struct
      include Ops_fd(struct
      let fd = Unix.openfile S.filename [ Unix.O_RDONLY ] 0
      end)
      end

      (* Usage example *)
      let () =
      let module Op = Ops(struct let filename="csw.dwg" end ) in
      ignore (Op.letter 1) ;
      Op.close ()
      ;;
      (* Or *)
      module Op' = Ops(struct let filename="csw.dwg" end )
      open Op'
      let () =
      ignore (letter 1) ;
      close ()
      ;; (* I'd prefer first variant to avoid namespace cluttering *)
      (* code ends *)

      The pure functional approach is to avoid usng implicit state at all and use something like
      let lastp a ix = _lastp a.{ ix };;
      let wordp a ix = _wordp a.{ ix };;
      let letter a ix = _letter a.{ ix };;
      let ptr a ix = _ptr a.{ ix };;
      probably making shorthands for actual usage like
      let a = .... in
      ...
      let ( ~! ) = lastp a in ...

      And objects are also quite a natural solution here, so it is a question of taste entirely :)
      --
      Good luck, Igor Borski
    • Show all 12 messages in this topic