Post At41tDKC62fioXI5Tc by pedromj@mastodon.social
(DIR) More posts by pedromj@mastodon.social
(DIR) Post #At22f4w8CKIsNmwIam by screwtape@mastodon.sdf.org
2025-04-13T00:36:20Z
0 likes, 1 repeats
@pedromj did you write your fibonacci numbers function in hy? I was curious how they connected.
(DIR) Post #At41tDKC62fioXI5Tc by pedromj@mastodon.social
2025-04-13T11:42:55Z
0 likes, 0 repeats
@screwtape I have three versions n Hy. I was trying to fully understand your code and see what is happening underneath. It is quite clear now. Thank you.I have three versions now.This is the closest to your version:```(defn fibonacci3 [n] (setv [prev curr] [0 1]) (for [_ (range 1 n)] (setv [prev curr] [curr (+ prev curr)])) curr)```
(DIR) Post #At41tEZpROlwhJc5U8 by pedromj@mastodon.social
2025-04-13T11:43:46Z
0 likes, 0 repeats
@screwtape This is using tail recursion (from the hyrule macro library):```(defn fibonacci2 [n] (loop [[n n] [prev 0] [curr 1]] (cond (or (= n 0) (= n 1)) curr True (recur (- n 1) curr (+ prev curr)))))```This a plain recursive version:```(defn fibonacci1 [n [prev 0] [curr 1]] (cond (or (= n 0) (= n 1)) curr True (fibonacci1 (- n 1) curr (+ prev curr))))```
(DIR) Post #At41tFHmnxvyteBC08 by screwtape@mastodon.sdf.org
2025-04-13T23:30:17Z
0 likes, 1 repeats
@pedromj seeing your iterative and recursive ones helped me see what I was /meant/ to do with series (which should be lazy and declarative):``` #commonLisp #series (defun better-fibs (n &optional (x-1 0) (x-0 1)) (let* ((range (scan-range)) (fibonacci-series (#M(lambda (n)(declare (ignore n))(psetq x-1 x-0 x-0 (+ x-1 x-0))(values x-0)) range))) (collect-nth n fibonacci-series)))```CL-USER> (better-fibs 4)8(Edit: (scan-range) on its own is just 𝗡)
(DIR) Post #At41tG1W3wVvBTZiHQ by screwtape@mastodon.sdf.org
2025-04-13T23:36:33Z
0 likes, 1 repeats
@pedromj your fibonacci3 in lisp, similar to my non-lazy iterate attempt would be phrased like this with the loop facility:(defun cl-fibonacci3 (n) (loop :With x-1 := 0 :with x-0 := 1 :repeat (1+ n) :for new-x := (+ x-1 x-0) :do (setq x-1 x-0 x-0 new-x) :finally (return x-0)))and your recursive-loop version is specifically jackdaniel's DO one.(Sorry for the off-by-one off-by-one errors, it seems ambiguous to me where the count to n 'should start')
(DIR) Post #At4Hy2JO4JHtN9Ec7s by ksaj@infosec.exchange
2025-04-14T02:28:05Z
0 likes, 1 repeats
@screwtape @pedromj Remember the one I wrote?(defun fib-nth (n) "KSAJ's speedy way to calculate nth Fibonacci number."(if (> n 1) (progn (decf n)(logand (truncate (ash 4 (* n (+ 3 n)))(- (ash 4 (* 2 n)) (ash 2 n) 1))(- (ash 2 n) 1)))n))Your off-by-one is probably the same thing I solved with that (decf n). Try it with that line commented out and see if your results match.