3

I've been going through problems in 4Clojure. There's Problem 26 which requires you to generate first n Fibonacci numbers. I wanted to solve it using lazy sequences and anonymous functions and this is my solution:

#(let [fib-seq (lazy-seq (map +
  (cons 0 (cons 0 fib-seq))
  (cons 1 fib-seq)))]
   (take % fib-seq))

It works fine when I test it on various arguments in CIDER (Emacs), but 4clojure rejects this solution giving the following exception:

java.lang.RuntimeException: Unable to resolve symbol: fib-seq in this context, compiling:(NO_SOURCE_PATH:0)

Do you have any idea why they might behave inconsistently? My local version of Clojure is 1.5.1

EDIT: Here's what worked for me in the end:

#(letfn [(fib-seq []
    ((fn rfib [a b] 
        (cons a (lazy-seq (rfib b (+ a b)))))
            1 1))]
    (take % (fib-seq)))

2 Answers 2

3

I suspect you have a fib-seq var in your REPL session. This will not work in a fresh REPL. A binding in let cannot refer to its left-hand side. That is, in Scheme parlance Clojure's let is not a letrec. You could do this with letfn instead.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured out the letfn solution in the meantime :). Thanks.
0

the version of clojure.jar used in 4clojure is before 1.5, because the function reduced(supported in clojure.1.5) is not supported in 4clojure

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.