Browse thread
[Caml-list] Hashtable, possible?
-
Lukasz Lew
-
Remi Vanicat
-
Remi Vanicat
-
Lukasz Lew
- Eray Ozkural
- Jacques Garrigue
-
Lukasz Lew
-
Remi Vanicat
-
Remi Vanicat
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Jacques Garrigue <garrigue@k...> |
| Subject: | Re: [Caml-list] Hashtable, possible? |
From: Lukasz Lew <ll189417@zodiac.mimuw.edu.pl>
>> Is it possible to implement with camlp4, syntax for using hashtables like
>> arrays?
[...]
> So. If it is possibe, and there is such syntax for arrays, strings and
> bigarrays, so why there isn't any for hashtables?
> I belive hashtables are more often used than bigarrays...
Maybe, but code using hash tables does not access/modify them several
times on the same line...
There is also a reasonnable concern about not having too many fancy
notations in the language.
Last, as ocaml does not use camlp4 by default, the answer to your
question would not imply that this is possible in ocaml alone.
However, if you are not using bigarrays, you can actually reuse their
notation in the vanilla compiler, by just defining the following
module:
# module Bigarray = struct
module Array1 =
struct let set = Hashtbl.add let get = Hashtbl.find end
end;;
module Bigarray :
sig
module Array1 :
sig
val set : ('a, 'b) Hashtbl.t -> 'a -> 'b -> unit
val get : ('a, 'b) Hashtbl.t -> 'a -> 'b
end
end
# let f x y z = x.{y} <- z;;
val f : ('a, 'b) Hashtbl.t -> 'a -> 'b -> unit = <fun>
# let g x y = x.{y};;
val g : ('a, 'b) Hashtbl.t -> 'a -> 'b = <fun>
However you probably also want sugar for hash table creation, and this
would indeed require camlp4:
{|"a" => 1; "b" => 2|}
But you can still do a lot with simple functions:
# let (=>) x y = (x,y);;
val ( => ) : 'a -> 'b -> 'a * 'b = <fun>
# let hash l =
let h = Hashtbl.create (max 7 (List.length l)) in
List.iter (fun (k,d) -> h.{k} <- d) l;
h;;
val hash : ('a * 'b) list -> ('a, 'b) Hashtbl.t = <fun>
# let h = hash["a"=>1;"b"=>2];;
val h : (string, int) Hashtbl.t = <abstr>
# h.{"a"};;
- : int = 1
---------------------------------------------------------------------------
Jacques Garrigue Kyoto University garrigue at kurims.kyoto-u.ac.jp
<A HREF=http://wwwfun.kurims.kyoto-u.ac.jp/~garrigue/>JG</A>
-------------------
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