有什么特殊的原因需要字符串中的模式吗?
Erlang 中不存在这样的模式,它们实际上只能出现在代码中。另一种方法是使用与 ETS match 和 select 相同的约定并编写自己的匹配函数。这真的很简单。 ETS 约定使用一个术语来表示原子'$1'、'$2' 等用作可以绑定和测试的变量的模式,'_' 是无关变量。因此,您的示例模式将变为:
{book,'_'}
{ebook,'_'}
{dvd,"The Godfather"}
这可能是最有效的方法。这里有可能使用匹配规范,但这会使代码复杂化。这取决于您需要多复杂的匹配。
编辑:
我为匹配器的一部分添加了不带注释的代码:
%% match(Pattern, Value) -> {yes,Bindings} | no.
match(Pat, Val) ->
match(Pat, Val, orddict:new()).
match([H|T], [V|Vs], Bs0) ->
case match(H, V, Bs0) of
{yes,Bs1} -> match(T, Vs, Bs1);
no -> no
end;
match('_', _, Bs) -> {yes,Bs}; %Don't care variable
match(P, V, Bs) when is_atom(P) ->
case is_variable(P) of
true -> match_var(P, V, Bs); %Variable atom like '$1'
false ->
%% P just an atom.
if P =:= V -> {yes,Bs};
true -> no
end
end.
match_var(P, V, Bs) ->
case orddict:find(P, Bs) of
{ok,B} when B =:= V -> {yes,Bs};
{ok,_} -> no;
error -> {yes,orddict:store(P, V, Bs)}
end.