[英]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 编辑:取5个小数给出[0,1,1,2,3]的列表,因此第5个元素的值为3,要提取它,我们必须键入:'last(take(5 fibs))'然后我们得到3.依此类推
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? 如果我们使用解释器寻找第5个元素,我们得到[0,1,2,3]的列表,最后一个元素与第5个元素的值相同,那么如何获取该列表的LAST元素? Can I 'make' it using
last
, do you have any ideas, could you? 我可以使用
last
“制作”它吗,您有任何想法吗?
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 (ie, not fibs
but, for example, take n fibs
for some n
) list, you can indeed obtain its last element by applying last
to it. 我不清楚您要问的是什么,但是如果您有一个非空的非无限(即没有
fibs
,例如,对于某些n
take n fibs
)列表,则确实可以通过以下方式获取其最后一个元素last
应用它。 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
另外,如果您只想要列表的第n个元素(从零开始并假定列表至少包含n + 1个元素),则可以执行
listName !! n
listName !! n
to extract it. listName !! n
提取它。
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: 如果您想要前10个元素的总和:
sum (take 10 fibs)
BTW there is a slightly simpler expression for fibs, using just recursion: 顺便说一句,对于fib来说,有一个稍微简单的表达式,只使用递归:
fibs = (fibgen 0 1) where fibgen a b = a : fibgen b (a+b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.