I'm trying to implement recursive algorithm solving Tower of Hanoi problem in Sightly. I know this approach may not have many obvious practical applications, I treat it as a puzzle. I end up with something like this:
<sly data-sly-template.step="${@ n, src, aux, dst}" data-sly-unwrap>
<sly data-sly-test="${n > 0}" data-sly-unwrap>
<sly data-sly-call="${step @ n = (n-1), src = src, aux = dst, dst = aux}" data-sly-unwrap/>
${src} -> ${dst}<br/>
<sly data-sly-call="${step @ n = (n-1), src = aux, aux = src, dst = dst}" data-sly-unwrap/>
</sly>
</sly>
<sly data-sly-call="${step @ n = 3, src = 'A', aux = 'B', dst = 'C'}" data-sly-unwrap/>
However, it doesn't compile as the Sightly doesn't support arithmetic
operators like -
. I don't need to count from 3 to 0, we may do it the
opposite way, as the direction doesn't matter here. I just need some
kind of counter with following features:
I thought about using string. Empty string would be zero, 'x' would be
1, 'xx' would be 2 and so on. We can check if a string equals to a
number (n == 'xxxx'
). We can even increment it, using Sightly string
formatter:
${'x{0}' @ format = [n]}
However, the above expression can't be used as a parameter in the
data-sly-call
or in the data-sly-test
. We can only display it
immediately and no further processing is available.
Do you have any other idea if there is some counter I can use?
Use empty nested arrays: []
is 0, [[]]
is 1, [[[]]]
is 2, etc.
If n
is a number then:
n[0]
decrements it (as we get the inner array),[n]
increments it (as we wrap the n
with a new array),data-sly-test
will accept all n > 0 (at least two opening brackets).The working code for n=3 would look like this:
<sly data-sly-template.step="${@ n, src, aux, dst}" data-sly-unwrap>
<sly data-sly-test="${n}" data-sly-unwrap>
<sly data-sly-call="${step @ n = n[0], src = src, aux = dst, dst = aux}" data-sly-unwrap/>
${src} -> ${dst}<br/>
<sly data-sly-call="${step @ n = n[0], src = aux, aux = src, dst = dst}" data-sly-unwrap/>
</sly>
</sly>
<sly data-sly-call="${step @ n = [[[[]]]], src = 'A', aux = 'B', dst = 'C'}" data-sly-unwrap/>
The interesting thing here is that such construction of integers is very similar to the set-theoretic definition of natural numbers. It appears that Maths is useful in the web-development after all!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With