Arne Babenhauserheide <arne_...@web.de> writes: > Hi, > > I just recreated a fluid advection exercise in Guile Scheme and I’m not > quite happy with its readability. Can you help me improve it? > > My main gripe is that the math does not look instantly accessible. > > The original version was in Python: > > psi[i] - c1*(psi[i+1] - psi[i-1]) + c2*(psi[i+1] - 2.0*psi[i] + psi[i-1]) > > My port to Scheme looks like this: > > (let ((newvalue (+ (- (psir i) > (* c1 (- (psir (+ i 1)) (psir (- i 1))))) > (* c2 (+ (- (psir (+ i 1)) (* 2 (psir i))) > (psir (- i 1))))))) > (array-set! psinew newvalue i))
Guile supports SRFI-105, so that could be: {{psi[i] - {c1 * {psi[{i + 1}] - psi[{i - 1}]}}} + {c2 * {{psi[{i + 1}] - {2 * psi[i]}} + psi[{i - 1}]}}} which is less readable than the Python version because there's no first-hand support for operator precedence so we {} group all binary operations, plus we need to use {} within [], plus we must separate operators with whitespace, but maybe it's acceptable. You can put "#!curly-infix" at the start of your Scheme file to enable SRFI-105 syntax. Note that all those 'psi[x]' expressions will expand to ($bracket-apply$ psi x) and you can implement a macro of that name to turn that into whatever is suitable at compile-time. (If performance is not an issue, SRFI-123 provides a run-time polymorphic procedure for $bracket-access$.) With a smart definition of $bracket-apply$, you could also cut down those psi[{i + 1}] to psi[i + 1]. The latter will expand to ($bracket-apply$ psi i + 1) which could be accommodated for in a special-purpose definition of $bracket-apply$ such as: (syntax-rules () ((_ obj index) (obj index)) ((_ obj x operator y) (obj (operator x y)))) That would *not* support e.g. psi[i + j - 1], which would instead need to be written e.g. psi[{i + j} - 1], i.e. we only save one pair of {}, but maybe that's good enough. By the way, e.g. {x - y + z} will turn into ($nfx$ x - y + z), and maybe there's a definition for $nfx$ out in the wild (or you can create one) that does operator precedence. (That could then also be used in $bracket-apply$.) So optimally, the whole thing could become: {psi[i] - c1 * {psi[i + 1] - psi[i - 1]} + c2 * {psi[i + 1] - 2 * psi[i] + psi[i - 1]}} Taylan