理解 Haskell 的斐波那契数列 [英] Understanding Haskell's fibonacci
问题描述
fibs :: [Int]
fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]
这会生成斐波那契数列.
This generates the Fibonacci sequence.
我理解 :
、zip
和 tail
守卫的行为,但我不理解 <- 代码>.它在这里做什么?
I understand the behaviour of the guards, of :
, zip
and tail
, but I don't understand <-
. What is it doing here?
推荐答案
由于点赞,我将评论变成了答案.
Due to the upvotes I made my comment into an answer.
你看到的不是守卫,而是列表理解.首先,将其视为一种表达数学集合符号的方式,例如 A = { x |x 元素 N } 表示以下内容: 集合 A 是所有自然数的集合.在列表理解中,这将是 [x |x <- [1..] ]
.
What you see is not a guard but it is list comprehension. For starters think of it as a way to express a mathematical set notation like A = { x | x element N } which means something along the lines of: The set A is the set of all natural numbers. In list comprehension that would be [x | x <- [1..] ]
.
您还可以对数字使用约束:[x |x <- [1..], x `mod` 2 == 0 ]
和许多其他的东西.
You can also use constraints on your numbers: [x | x <- [1..], x `mod` 2 == 0 ]
and many other things.
有很多不错的haskell turorials,涵盖了列表理解,甚至还有一个关于haskell 资源的StackOverflow 问题.
There are alot of good haskell turorials out there that cover list comprehension and even a StackOverflow question regarding haskell resources.
这篇关于理解 Haskell 的斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!