lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Sep 23, 2010 at 5:29 PM, Scott Vokes <vokes.s@gmail.com> wrote:
> I wrote a library to do Erlang-style pattern matching in Lua. Rather
> than writing a series of nested ifs to test/switch on a table's
> structure, you can just specify the table itself, possibly with
> variable captures. Pattern strings are also supported.
> ...For usage examples, see the README, API docs, benchmark, and test
> suite. More documentation and a rockspec will come soon.

Presently, I think the README.md is confusing [*], but the test.lua
makes things very clear.  It also suggests a simple but powerful
design, analogous to Lua's match/gsub but on structures, yet not on
the same level of XSLT/jQuery in tree handling capabilities.

I don't entirely like the idea of strings being interpreted as string
patterns rather than strings; string patterns could be encoded
specially in similar manner to how variables are with V.  Strings
passed into structural patterns as variables rather than as literals
might be misinterpreted as string patterns, leading to subtle bugs.
Lua's string library does the same thing though, apart from the
`plain` parameter on string.find, and concerns have been raised on
that [1-2].

The module looks promising and might in theory have general
application to type checking and tree handling code like for AST and
XML, but I wonder where it's worth it in practice.  Although I haven't
gotten in the habit of using it, Fabien has in fact implemented a
structural pattern matching library and syntax extension in the
context of Metalua for AST manipulation [3-4].  There seem to be a few
difficulties with applying tamale as is in such contexts though.
First, tamale does exact matches but seems limited in handling
unanchored matches and partial matches, such as to test whether an
object is a table containing a field 'tag' equal to 'String', not
caring whether the table contains any other fields (i.e. type(o) ==
'table' and o.tag == 'String').  tamale does support variable
captures, but I don't think it supports the concept of an "unknown
number of fields".  Alternation also comes up, e.g. pattern {tag =
Or{'foo', 'bar'}}, although tamale does in a limited way support that
by passing multiple patterns to tamale.matcher.

[1] http://lua-users.org/lists/lua-l/2005-09/msg00122.html
[2] http://lua-users.org/lists/lua-l/2008-09/msg00431.html
[3] http://metalua.luaforge.net/manual004.html
[4] http://github.com/fab13n/metalua/blob/master/src/lib/metalua/walk.mlua
[*] just one example: replace "when=valid_address(t)" with "when=valid_address"