Reputation: 4077
I want to check parameter is dict type or not in the 'where' expression, but can't find it in the erlang reference book.
init(Module_symbol_dict) where ???(Module_symbol_dict) ->
#state{module_symbol_dict=Module_symbol_dict}.
If I write it manually, it is can't be used in the where expression. What should do?
Upvotes: 0
Views: 683
Reputation: 3685
If you want to check if something is a dict, you can try keying off the first element in the dict tuple. While the implementation may change in the future, I doubt the first element being dict
will change. Try the guards I used in this function:
checkdict.erl
-module(checkdict).
-export([checkdict/1]).
checkdict(DictCand) when is_tuple(DictCand) andalso element(1, DictCand) =:= dict ->
is_dict;
checkdict(_NotDict) ->
not_dict.
Test:
Erlang R15B03 (erts-5.9.3.1) [source] [64-bit] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]
Eshell V5.9.3.1 (abort with ^G)
1> c(checkdict).
{ok,checkdict}
2> checkdict:checkdict(a).
not_dict
3> checkdict:checkdict(dict:new()).
is_dict
4> checkdict:checkdict({some, other, tuple}).
not_dict
5>
Upvotes: 2
Reputation: 2040
There is no way to check if the type of variable is dictionary or another nonstandard type. However there are some tricks. We can find out what exactly dictionary is. Launch Erlang shell and type:
> dict:new().
{dict,0,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}}}
So we see - dict itself is a tuple which have specific structure - it consists of 9 elements and its first element is an atom 'dict'. So in your example we can check whether variable is dict:
init({dict, _, _, _, _, _, _, _, _} = Module_symbol_dict) ->
#state{module_symbol_dict=Module_symbol_dict}.
You can improve it adding checks for other elements of dict tuple.
Note however - I'm afraid this is not very good way, because dict is internal type of dict module and programmer should use it as a blackbox. They may change the difinition of dict structure in future Erlang releases.
Upvotes: 1