[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: I wrote fluid advection code: How to make this more elegant?
From: |
Arne Babenhauserheide |
Subject: |
Re: I wrote fluid advection code: How to make this more elegant? |
Date: |
Sun, 24 Jan 2016 18:24:22 +0100 |
User-agent: |
mu4e 0.9.15; emacs 24.5.1 |
Taylan Ulrich Bayırlı/Kammer writes:
> Arne Babenhauserheide <address@hidden> writes:
>> 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}]}}}
That’s already pretty close — I wonder why I didn’t think of the psi[i]
form.
I think a + around the equation would actually help here:
(+ psi[i]
(* -1 c1 {psi[{i + 1}] - psi[{i - 1}]})
(* c2 {{psi[{i + 1}] - {2 * psi[i]}} + psi[{i - 1}]}))
Though neoteric expressions combined with curly infix make this even
easier: p{i + 1} → (p (+ i 1))
(though this did not work for me in the REPL right now — did I miss something?)
So the function psir could be used to have elegant access to elements:
(+ psi[i]
(* -1 c1 {psi[{i + 1}] - psi[{i - 1}]})
(* c2 {{psi[{i + 1}] - {2 * psi[i]}} + psi[{i - 1}]}))
> {psi[i] - c1 * {psi[i + 1] - psi[i - 1]} + c2 * {psi[i + 1] - 2 * psi[i]
> + psi[i - 1]}}
That looks roughly as readable as the Python version. With the + around
I think it becomes better:
(+ psi[i]
(* -1 c1 {psi[i + 1] - psi[i - 1]})
(* c2 {{psi[i + 1] - {2 * psi[i]}} + psi[i - 1]}))
And I don’t think it’s worse than the Python version, because in Python
I also need to first import numpy which changes some semantics (the []
operator changes and arrays have some special properties which can
sometimes bite).
Besides: when working on the Python, I was tempted to bracket the
expression to make it easier to split the lines and make the boundary
between sub-expressions clearer:
(psi[i]
- c1*(psi[i+1] - psi[i-1])
+ c2*(psi[i+1] - 2.0*psi[i] + psi[i-1]))
Best wishes,
Arne
PS: CCed to David A. Wheeler who wrote SRFI-105.
--
Unpolitisch sein
heißt politisch sein
ohne es zu merken
signature.asc
Description: PGP signature