Fibonacci sequence value in haskell
how to get sum of fibonacci sequence using that 开发者_开发技巧code:
fibs= 0 : 1 : zipWith (+) fibs (tail fibs)
edit: take 5 fibs gives list of [0,1,1,2,3], so the value of 5th element is 3, to extract it we have to type : 'last(take(5 fibs))' and we get 3. And so on
if we use interpreter to seek for 5th element we get list of [ 0, 1, 2, 3] the last element is the same what value of 5th element, how to get LAST element of that list?
Can I 'make' it using last
, do you have any ideas, could you?
That definition yields an infinite stream of integers. There is no last element.
If instead you want to index a particular element from the list, you can do so with the (!!)
operator:
> [1..] !! 7
8
I'm not entirely clear what you're asking, but if you have a non-empty non-infinite (i.e., not fibs
but, for example, take n fibs
for some n
) list, you can indeed obtain its last element by applying last
to it. Alternatively, if you just want the n-th element of a list (starting at zero and assuming the list has at least n+1 elements), you can do listName !! n
to extract it.
Well, if you just want the 10th element of the list:
last (take 10 fibs)
if you want the sum of the first 10 elements:
sum (take 10 fibs)
BTW there is a slightly simpler expression for fibs, using just recursion:
fibs = (fibgen 0 1) where fibgen a b = a : fibgen b (a+b)
精彩评论