Jump to content

Periodic table: Difference between revisions

m
Adds memoization function.
(Inserts Scheme)
m (Adds memoization function.)
Line 1,260:
 
=={{header|Scheme}}==
The following is minimal recursive implementation. It calculates the position of the requested element by the position of the previous element.
<syntaxhighlight lang="scheme">(define (position-increment n)
(cond
Line 1,299 ⟶ 1,300:
(format-line n (position n)))
(list 1 2 29 42 57 58 72 89))</syntaxhighlight>
For successive calculations the above code is inefficient, because the position of 58 gets calculated by recalculating the position of 57, although is has already been calculated in the previous step. This can be enhanced by the use of memoization. The result of each calculation gets stored and whenever a position has to be calculated, the already calculated value gets used instead.
<syntaxhighlight lang="scheme">(define position*
(let ((memo (make-vector 118 #f)))
(lambda (n)
(let* ((mi (- n 1))
(mp (vector-ref memo mi)))
(or mp
(let ((p (position n)))
(vector-set! memo mi p)
p))))))</syntaxhighlight>
{{out}}
<pre>1 -> 1 1
9

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.