Reputation: 1047
This is a way to get the Fibonacci sequence in Haskell. It's from the book haskellbook.com (supposedly for beginners):
fibs = 1 : scanl (+) 1 fibs
I can only "see" that this is Fibonacci after writing out a few of the first elements manually:
1 : scanl (+) 1 (1 : scanl (+) 1 (1 : scanl (+) 1 (1 : 1 ...
1 : scanl (+) 1 (1 : scanl (+) 1 (1 : 1 : 2 : 3 ...
1 : scanl (+) 1 (1 : 1 : 2 : 3 : 5 : 8 ...
1 : 1 : 2 : 3 : 5 : 8 : 13 : 21 ...
Only now do I have some intuition into why this is the Fibonacci sequence. But I had to write it out like this first. And even then it's still just an intuition, not solid proof.
I have three questions:
Upvotes: 3
Views: 371
Reputation: 120711
Was I supposed to immediately just spot the Fibonacci sequence from the original line?
Heck no! You were supposed to read the example, scratch your head, write it out manually... and thereby get an intuition for how scanl
works and why this can be used for Fibonacci numbers.
Would some of you ... have seen that the original line is the Fibonacci sequence?
Well, it is called fibs
... apart from that, yeah, scanl
is standard enough that an experienced programmer would quickly see what's going on.
pretty sure Haskell requires a higher IQ
I think Haskell requires most of all a good deal of stubbornness, and a particular sense of æsthetics. Haskell has some quirky ways of doing stuff different. Some of these are a bit hard to grasp, but most of all they're just unfamiliar to most programmers. It's all about getting used to the stuff.
And because, if we're honest, Haskell skills are still not a terribly utilitarian thing right now (as in, any real-world task can be solved as well by some other language too), you really need some enthusiasm for the language's beauty and future potential to keep up with it.
Note that Haskell's quirks and features have a tendency to slowly seep into mainstream languages. So, even if “Haskell is not for you” you may in the long term benefit from the nice things that are prototyped here, perhaps without even noticing where they come from.
Upvotes: 11
Reputation: 5813
Upvotes: 4