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)))
有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top