Doesn't iteration function save intermediate steps?

I was just starting to study Haskell and how the exercise got into the Project Euler problem, where the Fibonacci numbers were. My current method is this function, which creates a new list with the following element:

fib :: (Integral a) => [a] -> [a] fib xs@ (x1:x2:_) = (x1+x2) : xs 

I found an iterate function that returns a function on the result. However, the result is a list of lists, [[2,1],[3,2,1],[5,3,2,1],..] . What is the iterate alternative when I'm not interested in intermediate results? I want to make takeWhile with a condition for the last generated number. Is it not at all to think about it?

(I saw better / shorter / faster ways to generate a Fibonacci sequence, so I am not looking for feedback on the fib function, but I would like to make it work, a suboptimal method or not)

+4
source share
4 answers

Just use iterate ! Since Haskell is a pure language, all subscribers get shared access, and you pay almost no cost for creating all these mini-lists: [2, 1] actually 2, 1 in [3, 2, 1] , etc. .

You really don't want to takeWhile , because it will give you a lot of superfluous anthill, and you still need to get to the end with last . Use find instead.

Also note that if you plan to summarize the resulting list, you skipped 1 , so you will have one.

+3
source

I'm not sure about using iterate , but see Haskell's Filtering the Fibonacci Sequence for a list of fibs.

Is it the same homework?

0
source

I would use take, as each subsequent approximation will be one whole more accurate than the last. Then you can do (reverse).

Note that β€œevery” result is an intermediate result if the function you execute does not have a computable fixed point.

0
source

When you need a function in Haskell, just define it :)

The following is not the most elegant or idiomatic Haskell, but serves to show that you can always do something manually using a tail recursive loop if necessary

 apply_n fnx = if n = 0 then x else apply_n' f (n-1) (fx) n_th_fib n = apply_n fib n [1,1] 

I am sure there is an easier way to do this using folds (or a library function that I forgot about :))

0
source

All Articles