[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: |
Taylan Ulrich Bayırlı/Kammer |
Subject: |
Re: I wrote fluid advection code: How to make this more elegant? |
Date: |
Sun, 24 Jan 2016 18:46:43 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) |
Arne Babenhauserheide <address@hidden> writes:
> 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))
Good call, I had forgotten that's included in SRFI 105. (Thought it was
just for x[y].)
> (though this did not work for me in the REPL right now — did I miss
> something?)
Any SRFI 105 syntax must appear within {}, so that would have to be
e.g. {p{i + 1}}, although if it appears within a larger {} block then it
won't have that annoyance.
> 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]}))
I agree mixing in some prefix notation actually makes things more
readable here.
Taylan