Created
September 14, 2018 12:48
-
-
Save nedzadarek/43878a2eedd31c793e35eac854bcfe3d to your computer and use it in GitHub Desktop.
Fibonacci with cache and serializing cache to a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Red [ | |
author: "Nędza Darek" | |
license: "Just point to this gist/github" | |
link: https://gist.github.com/nedzadarek/43878a2eedd31c793e35eac854bcfe3d | |
] | |
; if `n` is in the cache just return `n` else print ['not-cached n] | |
fib: function [n] bind [ | |
cache | |
either c: cache/:n [ | |
return c | |
][ | |
print ['not-cached n] | |
cache/:n: (fib (n - 1)) + (fib (n - 2)) | |
] | |
] context [ | |
cache: #( | |
0 0 | |
1 1 | |
) | |
] | |
fib 10 | |
; not-cached 10 | |
; not-cached 9 | |
; not-cached 8 | |
; not-cached 7 | |
; not-cached 6 | |
; not-cached 5 | |
; not-cached 4 | |
; not-cached 3 | |
; not-cached 2 | |
; == 55 | |
fib 10 | |
; == 55 | |
saved-cache: mold cache: context? first body-of :fib | |
replace saved-cache "make object!" "context" | |
print saved-cache | |
; context [ | |
; cache: #( | |
; 0 0 | |
; 1 1 | |
; 2 1 | |
; 3 2 | |
; 4 3 | |
; 5 5 | |
; 6 8 | |
; 7 13 | |
; 8 21 | |
; 9 34 | |
; 10 55 | |
; ) | |
; ] | |
; clearing cache (setting just zero and one index to make fibonacci work) | |
cache/cache: #(0 0 1 1) | |
fib 10 | |
; not-cached 10 | |
; not-cached 9 | |
; not-cached 8 | |
; not-cached 7 | |
; not-cached 6 | |
; not-cached 5 | |
; not-cached 4 | |
; not-cached 3 | |
; not-cached 2 | |
; == 55 | |
fib 10 | |
; == 55 | |
cache/cache: #(0 0 1 1) | |
loaded-s: load saved-cache | |
if 'context = first loaded-s [ | |
old-cache: select (context? first (body-of :fib)) 'cache | |
new-cache: select (context loaded-s/2) 'cache | |
extend old-cache new-cache | |
probe context? first body-of :fib | |
] | |
; 10 is in the cache: | |
fib 10 | |
; == 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Insert cache directly inside body: https://gitter.im/red/help?at=5b9bb126d655361f76fb7c7b