3 ms·
Apart from non-strict evaluation, the example doesn't use any primitives which are not extremely common in any functional programming language: -- list con
by nybble41 9y ago
Apart from non-strict evaluation, the example doesn't use any primitives which are not extremely common in any functional programming language:
-- list constructor
1 : 2 : 3 : [] == [1,2,3]
-- remove first item from a list
tail [1,2,3] == [2,3]
-- combine two lists "pointwise"
zipWith (+) [1,2] [3,4] == [1+3,2+4]
If you line up the Fibonacci numbers starting from the first element and the Fibonacci numbers starting from the second element, and add the corresponding elements, you get the remaining elements of the Fibonacci sequence. Visually:
1, 1, (2, 3, 5, 8, 13, ...) -- fibs
1, (2, 3, 5, 8, 13, ...) -- tail fibs
+ ==========================
(2, 3, 5, 8, 13, ...) -- zipWith (+)
This declaration:
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
is merely the previous recurrence diagram translated into code. That is why I consider it an elegant definition.