• Subject: Re: [ANN] tamale-1.2 - Erlang-style pattern matching library
• From: steve donovan <steve.j.donovan@...>
• Date: Fri, 24 Sep 2010 12:48:24 +0200

```On Fri, Sep 24, 2010 at 1:36 AM, Patrick Mc(avery
> encountering a rather obvious problem, all the examples are in Erlang! A
> language I cannot program in.

Examples are always the best way:

\$ lua -ltamale
> function dump(t) for k,v in pairs(t) do print(k,v) end end
> V = tamale.var
> M = tamale.matcher{ {{V'X',V'Y',V'Z'},true} }
> res,t = M{10,20,30}
> = res
true
> dump(t)
Y	20
X	10
args	table: 0x9407780
input	table: 0x94074d0
Z	30

matcher() is given a set of pairs - the first element of a pair is the
pattern, the second is the value returned if the pattern matches. The
variable matches V() act like named captures; the result of applying
the function generated by matcher() (if successful) will be the value
and a table containing the captured values.

Otherwise, we get false:

> = M{10,20,30,40}
false	Match failed	table: 0x9408be0

The result can be a function, which will be called with the table of
values to give the actual result (e.g. function(t) return t.X + t.Y +
t.Z end) or can be a table with variable references

> M = tamale.matcher{ {{x=V'X',y=V'Y'},{V'X',V'Y'}} }
> dump(M {x = 10, y = 20})
1	10
2	20

This does a substitution operation, which is useful for restructuring tables.

In a typical use, tamale.matcher() is given a set of pairs, and the
first one matching will be the value, so it can be used as a
generalized lookup table.

As David points out, these are 'anchored' matches because they always
match from the beginning of the table.  (It would be interesting to
think what an unanchored match would look like in this case.)

I said to Scott that having 'varargs' matching would be very useful.
This is a problem that occurs often in processing complex table
structures, e.g. XML in LOM format

{tag = 'parent', {tag = 'children',
{tag = 'child', attr={age=V'Age'},V'Name'},
'...'  --> varargs ??
}}

where we want to indicate that there can be an indefinite number of
child elements. The result then of this match would be something like

{{Age='5',Name='Tommy'},{Age='7',Name='Anne'},...}

steve d.

```