[erlang-questions] Why does fun2ms produce this particular result?

Jachym Holecek freza@REDACTED
Sun May 1 21:53:59 CEST 2011


# Daniel Dormont 2011-05-01:
> I'm trying to get the hang of match specs. Here's a pretty simple one but it has a feature I'm not
> getting. It's intended for use with Mnesia:
> 
> 1> rd(person, {name, address, email, phone}).
> person
> 2> ets:fun2ms(fun(#person{name=Name, email=Email}) -> {Name, Email} end).                          
>   
> [{#person{name = '$1',address = '_',email = '$2',
>           phone = '_'},
>   [],
>   [{{'$1','$2'}}]}]
> 
> My first question was going to be why the whole thing is a single-element list, but I think I
> figured that out: it's because there could be multiple clauses of the match as a whole.

Correct.

About the rest, http://www.erlang.org/doc/man/ms_transform.html has some
information though I'm not sure it's exhaustive. Here's my understanding,
I'm sure someone will correct me if I'm wrong (remember that matchspecs
aren't just an ETS/Mnesia thing, there's also dbg(3) and there could be
other users eventually):

> The part I don't get is in the result: [{{'$1','$2'}}]
> 
> 1) Why is it a list at all, since a particular head in the function can only have one result?

Because it's a function body (sort of), that is: a sequence of expressions?

> 2) Why does the tuple have to be wrapped in another tuple? ie why isn't it just {'$1','$2'}

A way of quoting term constructions, to disambiguate them from other constructs
in matchspec language (whatever they might be)?

> For now I'm happy to just trust that fun2ms works, but I'd like to understand it a little better.

To be honest I never tried too hard -- matchspecs are a bit odd, but work great
once you get used to them... :-)

HTH,
	-- Jachym



More information about the erlang-questions mailing list