PicoLisp Explored: The cache function

The cache function

: (off C)  # empty cache 
-> NIL
# store some values in C
: (cache 'C 'c1 (* 3 4))
: (cache 'C 'c2 (* 4 5))
: (cache 'C 'c3 "hello")
: (cache 'C 'c4 "hello")
: (cache 'C 'c5 (+ 10 1))
: (depth C)
-> (4 . 3)
: C
-> (("볐" . c1) (("벪" . c2) (("粋" . c3) (("籇" . c5)) ("뱦" . c4))))
: (view C T)
("볐" . c1)
("벪" . c2)
("뱦" . c4)
("粋" . c3)
("籇" . c5)
: (val (cache 'C 'c5))
-> 11
: (val (cache 'C 'c1))
-> 12

Good old Fibonacci

: (de fibo (N)
(if (>= 2 N)
1
(+ (fibo (dec N)) (fibo (- N 2))) ) )
  • Step 1 fibo 5: calls fibo 4
  • Step 2 fibo 4 (from Step 1): calls fibo 3
  • Step 3 fibo 3 (from Step 1): calls fibo 2
  • Step 4 fibo 3 (from Step 2): calls fibo 2
  • Step 5 fibo 3 (from Step 4): calls fibo 1
  • Step 6 fibo 3 (from Step 3): calls fibo 1 .....

Cached Fibonacci

: (de fiboCache (N)
(cache '(NIL) N
(if (>= 2 N)
1
(+ (fiboCache (dec N)) (fiboCache (- N 2))) ) ) )
: (bench (fiboCache 10000))
0.101 sec
: (bench (fibo 30))
0.100 sec

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mia Temma

Mia Temma

These are cross-posts from my blog https://picolisp-explored.com. I’m writing about PicoLisp for beginners. Welcome!