[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: [Lpeg] Problem with Cf
- From: Pierre-Yves Gérardy <pygy79@...>
- Date: Sat, 12 Apr 2014 22:31:54 +0200
On Sat, Apr 12, 2014 at 10:01 PM, Christophe Devalland
<christophe.devalland@gmail.com> wrote:
> Hello,
> function parenthese(expression)
> return 'par{' .. expression .. '}'
> end
> [...]
> -- the following line doesn't work as expected : 1 + par{5}
> -- Parentheses=Open*Cf(Exp,parenthese)*Close,
You're looking for the function capture, and Cf is the folding capture.
Replace `Cf(Exp,parenthese)` with `(Exp/parenthese)`, you'll get the
expected result.
`fold` is a higher level function also known as `reduce`.
for example, with `add` defined as `function(a, b) return a + b end`,
`fold(add, {1,2,3,4})` will return 10. Here's an implementation:
function fold(func, array, first)
local i0 = 1
if first == nil then
first, i0 = array[1], 2
end
local accumulator = first
for i = i0, #array do
accumulator = func(accumulator, array[i])
end
return accumulator
end
The folding capture applies its second argument to the value of its
children captures in the same way.
On the other hand, the "function capture" applies the function once to
the values of all subcaptures.
—Pierre-Yves