[erlang-questions] questions about dict

Joe Armstrong erlang@REDACTED
Tue Aug 21 20:05:09 CEST 2007


You could put the dictionary in a record and test for the record :-)

Define dict.hrl

--- dict.hrl ---
-record(dict,{val}).

--- my_dict.erl ---

-module(my_dict).

-record(dict, {val}).
-export([new/0, store/3, find/2]).

new() ->
    #dict{val=dict:new()}.

store(Key, Val, Dict) ->
    #dict{val=dict:store(Key, Val, Dict#dict.val)}.

find(Key, Dict) ->
    dict:find(Key, Dict#dict.val).

Use can use my_dict.erl just as you would use dict

--- test1.erl ---

-module(test1).

-compile(export_all).

-include("dict.hrl").

test() ->
    D  = my_dict:new(),
    D1 = my_dict:store(name,joe,D),
    foo(D1).

foo(X) when is_record(X, dict) ->    %% This is how to fake a guard
    my_dict:find(name, X).

etc ...

If you *really* want to fake it up as a guard

The more "erlangy" way is to add a wrapper and use pattern matching:

foo({dict, X}) -> ...

the tuple {dict, X} is used *everywhere* in the code to
signal the fact that X is an instance of a dictionary - then you
just pattern match on {dict, X}

/Joe Armstrong

On 21 Aug 2007 09:27:49 +0200, Bjorn Gustavsson <bjorn@REDACTED> wrote:
> Dustin Sallings <dustin@REDACTED> writes:
>
> >
> > >>    2)  I can't seem to make a guard for a dict because the record
> > >> format is unavailable to me at compile time (I'm working around this
> > >> by matching tuple and hard-coding a tuple pattern for identifying a
> > >> dict).
> > >
> > > That is intentional (and even mentioned in the documentation).
> > >
> > > There is no portable way to test for a dict in a guard.
> >
> >       Where is this documented?  I looked around for a while and
> > couldn't  find anything either way.  There's clearly a gap in my
> > understanding  of guards, records, or dicts.
>
> It may be a little subtle, but the documentation for dict says:
>
>  "Dict implements a Key - Value dictionary. The representation of a dictionary is not defined."
>
> That means that only the dict module knows about how a dictionary is represented,
> and that you should only use the functions in the dict module to access a dictionary.
>
> If you use knowledge gained from looking at the source of dict to write a guard
> test any, your code could in principle stop to work in a future release of OTP if
> we change the representation.
>
> /Bjorn
>
> --
> Björn Gustavsson, Erlang/OTP, Ericsson AB
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list