15

Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:

Clojure:

(def fib-seq (lazy-cat [0 1]
 (map + fib-seq (rest fib-seq))))

sample usage:

 (take 5 fib-seq)

Python:

def fib():
 a = b = 1
 while True:
  yield a
  a,b = b,a+b

sample usage:

for i in fib():
  if i > 100:
    break
  else:
    print i

Obviously the Python code is much more intuitive.

My question is: Is there a better (more intuitive and simple) implementation in Clojure ?

Edit

I'm opening a follow up question at Clojure Prime Numbers

Community
  • 1
  • 1
Roskoto
  • 1,722
  • 1
  • 16
  • 27
  • 14
    Simplicity and intuitiveness are subjective. Not a real question IMHO. – Tadeusz A. Kadłubowski Oct 19 '09 at 07:54
  • 2
    @tkadlubo Fibonacci sequence is realty simple and I gave it just for example. But going beyond for a real world problems simplicity and intuitiveness always pays off. – Roskoto Oct 19 '09 at 08:13
  • 4
    Obviously, the Clojure code is much more intuitive. Is there a better (more concise and clearer) implementation in Python? – Svante Oct 19 '09 at 14:27
  • 5
    I don't think there's anything meaningfully subjective going on here. I understood programs written in BASIC in magazines when I was about 10 years old, before I'd ever seen a real computer. I'm sure I would have understood the python version too. I wouldn't have understood the clojure version until I'd read SICP. And I speak as a functional programming enthusiast whose preferred language is Clojure. We should stop trying to convince people that the fault is with them if they don't 'get it'. There are advantages to the functional way, but they don't come free. – John Lawrence Aspden Aug 24 '10 at 07:54
  • 1
    OBVIOUSLY the Python version is more intuitive, lol. My first thought was, "obviously the Clojure version is much superior" to each his own. – Alex Baranosky Jan 15 '11 at 22:20
  • 6
    *"Obviously the Python code is much more intuitive."* It's not. It's "more imperative", and for a lot of people imperative tends to be more obvious because that's what they're used to, but that is a matter of perception, and is strictly subjective. – Pavel Minaev Oct 19 '09 at 07:49

9 Answers9

36

I agree with Pavel, what is intuitive is subjective. Because I'm (slowly) starting to grok Haskell, I can tell what the Clojure code does, even though I've never written a line of Clojure in my life. So I would consider the Clojure line fairly intuitive, because I've seen it before and I'm adapting to a more functional mindset.

Let's consider the mathematical definition, shall we?

       { 0                   if x = 0 }
F(x) = { 1                   if x = 1 }
       { F(x - 1) + F(x - 2) if x > 1 }

This is less than ideal, formatting wise - those three brackets lined up should be one giant bracket - but who's counting? This is a pretty clear definition of the Fibonacci sequence to most people with a mathematical background. Let's look at the same thing in Haskell, because I know it better than Clojure:

fib 0 = 0
fib 1 = 1
fib n = fibs (n - 1) + fibs (n - 2)

This is a function, fib, that returns the nth Fibonacci number. Not exactly what we had in Python or Clojure, so let's fix that:

fibs = map fib [0..]

This makes fibs an infinite list of Fibonacci numbers. fibs !! 1 is 1, fibs !! 2 is 1, fibs !! 10 is 55, and so on. However, this is probably quite inefficient, even in a language that relies on heavily optimized recursion such as Haskell. Let's look at the Clojure definition in Haskell:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

The first couple of characters are pretty simple: 0 : 1 : makes a list with elements 0 and 1, and then some more. But what's all the rest of that? Well, fibs is the list we've already got, and tail fibs calls the tail function on our list so far, which returns the list starting at the 2nd element (sort of like in Python saying fibs[1:]). So we take these two lists - fibs and tail fibs - and we zip them together with the + function (operator) - that is, we add the matching elements of each. Let's look:

fibs       = 0 : 1 : ...
tail fibs  = 1 : ...
zip result = 1 : ...

So our next element is 1! But then we add that back onto our fibs list, and look what we get:

fibs       = 0 : 1 : 1 : ...
tail fibs  = 1 : 1 : ...
zip result = 1 : 2 : ...

What we have here is a recursive list definition. As we add more elements to the end of fibs with our zipWith (+) fibs (tail fibs) bit, more elements become avaliable for us to work with when adding elements. Note that Haskell by default is lazy, so just making an infinite list like that won't crash anything (just don't try to print it).

So while this is perhaps theoretically the same as our mathematical definition before, it saves the results in our fibs list (sort of an auto-memoization) and we rarely have the problems that might be experienced in a naive solution. For completeness, let's define our fib function in terms of our new fibs list:

fib n = fibs !! n

If I didn't lose you yet, that's good, because that means you understand the Clojure code. Look:

(def fib-seq (lazy-cat [0 1]
 (map + fib-seq (rest fib-seq))))

We make a list, fib-seq. It starts with two elements, [0 1], just like our Haskell example. We do a lazy concatenation of these two initial elements with (map + fib-seq (rest fib-seq)) - assuming rest does the same thing that tail does in Haskell, we're just combining our list with itself at a lower offset, and then combining these two lists with the + operator/function.

After working this through your head a few times, and exploring some other examples, this method of generating fibonacci series becomes at least semi-intuitive. It's at least intuitive enough for me to spot it in a language I don't know.

flash42
  • 71
  • 6
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
  • 5
    Chris, first thanks for the nice explanation it is useful in it's own way to someone trying to understand the Clojure code. But actually you've proved my point. The Python code doesn't need the huge explanation :) – Roskoto Oct 19 '09 at 08:54
  • 14
    The Python code has _had_ an explanation: about 50 years of imperative programming style has explained it to you. I wouldn't know much about either language's code if I didn't know programming. Granted, the Haskell/Clojure programs may hurt my brain a little more as I try to learn the languages, but really you consider them more readable/intuitive because you're used to imperative and procedural languages, like most programmers are. Learning a new mindset or paradigm is going to take a lot of explanation. How long did it take you to learn generators? Or pointers (if you know C)? – Chris Lutz Oct 19 '09 at 09:07
  • As I understand it the yield command denies the idea of call stack in general. I'm pretty sure it is not something common from the last 50 years (except the scheme's call/cc). I still insist that the sample Python code is far from imperative. – Roskoto Oct 19 '09 at 10:03
  • The yield concept isn't tremendously common, but it has been discussed by Knuth and at least implemented in C (though not shared) by Tom Duff by the time he invented his device in 1983 (http://www.lysator.liu.se/c/duffs-device.html - see the second to last paragraph), and generators specifically originated in 1975 from a language called CLU, which was procedural and object-oriented. And neither of the Wikipedia pages for "procedural programming" or "imperative programming" contain the word "stack." The call stack is not a fundamental concept for either paradigm, just an implementation detail. – Chris Lutz Oct 19 '09 at 17:00
  • 3
    `yield` is imperative. It doesn't have anything to do with the stack - if you issue commands ("statements" - `yield` in Python is a statement), then it's imperative. – Pavel Minaev Oct 19 '09 at 17:11
  • 1
    Thank you, Pavel, for the argument I should be making. Though at this point, I'd like to note that, since we've been arguing this long on what is and isn't intuitive to us, and since we disagree on what we found intuitive, you (Roskoto) are by definition wrong in your blanket assumption that X is more intuitive than Y for all programmers. – Chris Lutz Oct 19 '09 at 17:18
  • Is it true that everything that could be implemented with yield has its Clojure equivalent? I thought that if Clojure had this "feature" too it will be even better but looks like I'm the only one having this opinion. – Roskoto Oct 19 '09 at 19:25
  • 1
    In the worst case scenario, you could implement generators in Clojure yourself. Some people have already done so for Common Lisp, for example. Someone correct me if I'm wrong, but I don't think `yield` adds any power to the language; it's only syntax sugar. If even [plain old Java](http://en.wikipedia.org/wiki/Generator_%28computer_science%29#Other_Implementations) can do generators, Clojure can. – Brian Carper Oct 19 '09 at 21:44
  • @Brian - That's a rather scary thing to say. `if` and `else` are "only syntax sugar." `yield` (like any other language construct) adds no _physical_ power to the language, but it adds a lot of _expressive_ power, which makes code clearer and more readable. – Chris Lutz Oct 20 '09 at 01:17
  • 1
    No, conditionals aren't syntax sugar. In Lisps at least, you need at least one primitive conditional to build others out of it, because it has non-standard evaluation rules (it short-circuits). In Clojure, `if` is one of (very few) primitives and `cond` is a macro built using it. But `cond` could've been the primitive in which case `if` could be build out of that. Or they both could be built on some other primitive. I think `yield` in a Lisp would be a function or macro that you could write yourself without the need for more primitives, that's all I meant. – Brian Carper Oct 20 '09 at 01:54
  • @Brian - Ah. I was assuming that `goto` is the basic primitive flow control statement (well, variations on `jmp` with different conditions). I suppose Lisps might have a hard time dealing with `goto`s and labels in the syntax, though. – Chris Lutz Oct 20 '09 at 02:20
14

I like:

(def fibs 
  (map first 
       (iterate 
           (fn [[ a, b       ]]  
                [ b, (+ a b) ]) 
           [0, 1])))     

Which seems to have some similarities to the python/generator version.

John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110
  • Also this is much better! It seems like the version OP described also caches the whole seq in memory for functions like nth, defeating the purpose of lazy sequences. – FUD Sep 11 '13 at 08:22
12

If you didn't know any imperative languages, would this be intuitive for you?

a = a + 5

WTF? a clearly isn't the same as a + 5.

if a = a + 5, is a + 5 = a?

Why doesn't this work???

if (a = 5) { // should be == in most programming languages
    // do something
}

There are a lot of things that aren't clear unless you've seen it before somewhere else and understood its purpose. For a long time I haven't known the yield keyword and in effect I couldn't figure out what it did.

You think the imperative approach is more legible because you are used to it.

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
6

The Clojure code is intuitive to me (because I know Clojure). If you want something that might look more like something you're familiar with, you can try this, an efficient and overly-verbose recursive version:

(use 'clojure.contrib.def)   ; SO's syntax-highlighting still sucks
(defn-memo fib [n]
  (cond (= n 0) 0
        (= n 1) 1
        :else   (+ (fib (- n 1))
                   (fib (- n 2)))))

(def natural-numbers (iterate inc 0))

(def all-fibs
  (for [n natural-numbers]
    (fib n)))

But to someone who doesn't know what recursion or memoization are, that isn't going to be intuitive either. The very idea of "infinite lazy sequences" probably isn't intuitive to the majority of programmers. I can't guess what's in your brain so I don't know what a more intuitive Clojure function would look like to you, other than "looks more like Python".

To someone who doesn't know programming, all of this stuff is going to look like gibberish. What's a loop? What's a function? What is this yield thing? That's where we all start. Intuitiveness is a function of what you've learned so far. Non-intuitive code is code you aren't familiar with yet. Extrapolating from "I know this" to "It's inherently more intuitive" is wrong.

Brian Carper
  • 71,150
  • 28
  • 166
  • 168
  • 1
    for me intuitive = closer to the mathematical definition. – Roskoto Oct 19 '09 at 19:14
  • 5
    @Roskoto - Under that logic, the Clojure version is clearer than the Python version, since the Clojure version is functional and closer to actual math than the procedural Python version. – Chris Lutz Oct 20 '09 at 02:22
  • where is the memoization happening? the contrib.def? – Ravi Jan 07 '12 at 04:41
5

The wiki has an in depth treatment of various Fibonacci implementations in Clojure which may interest you if you haven't seen it already.

Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63
2

You should always use a language that fits the problem*. Your Python example is just lower level than the Clojure one -- easier to understand for beginners, but more tedious to write and parse for someone who knows the fitting higher level concepts.

* By the way, this also means that it is always nice to have a language that you can grow to fit.

Svante
  • 50,694
  • 11
  • 78
  • 122
2

Here is one solution.

(defn fib-seq [a b]
  (cons (+ a b) (lazy-seq (fib-seq (+ a b) a))))

(def fibs (concat [1 1] (fib-seq 1 1)))

user=> (take 10 fibs)
(1 1 2 3 5 8 13 21 34 55)
-1

Think about how would you write lazy-cat with recur in clojure.

Tadeusz A. Kadłubowski
  • 8,047
  • 1
  • 30
  • 37
-5
(take 5 fibs)

Seems about as intuitive as it could possibly get. I mean, that is exactly what you're doing. You don't even need to understand anything about the language, or even know what language that is, in order to know what should happen.

nilamo
  • 1,932
  • 13
  • 22