lua-users home
lua-l archive

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


On Fri, Sep 24, 2010 at 10:14 AM, Javier Guerra Giraldez
<javier@guerrag.com> wrote:
> instead of:  "xxx" is a constant, and "xx%d" is a match pattern, do:
> "xxx" is a constant and tamale.M("xx%d") is a match predicate (a
> closure that takes the target element and returns true or false).
...
> elseif t == 'function' then m = pat_element(targ_element) .....

The predicate idea is versatile, but as written that does prevent
matching functions literally.

To generalize that idea with a real example, one place where I use
structural pattern matching in Lua is for test suites, particularly to
check numerical computations.  For example, to check a function that
returns three values, the values would be wrapped in a tuple and
compared element-wise against the expected tuple using an
*approximate* equality operator to allow for numerical computational
error:

  TOL = 1e-10
  check('approx', tuple(f(2, 3)), tuple(5, 2, true))

Note also that I'm using tuples, not tables, to preserve any possible
(and perhaps inadvertent) trailing nil's in function return values.
Matching a value against a range, e.g. range(-1, 1), a type of
continuous alternation, can also come up.