在 Haskell 中过滤斐波那契数列
我正在尝试过滤包含斐波那契数字的列表。
我需要的只是奇数,并且小于或等于N
。
这就是我到目前为止所拥有的:
fib n | n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
fibs n = [a | a <- [fib x | x <- [1..]], odd a, a < n]
这会给我想要的东西,但同时该解决方案不起作用,因为我不知道如何停止从 fib
函数检索元素。当然,这是因为x <- [1..]
。
我考虑过两种选择:
- 在
x <- [1..]
中设置限制(取决于n
) - 定义
fibs
递归这样我就可以知道何时停止(在写问题时思考)
我该怎么做?
我不是在寻找一种有效的方法
编辑:
这是我最后得到的两个解决方案:
fib n | n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
fibsAux n k xs | a < n = fibsAux n (k+1) (xs ++ [a])
| otherwise = xs
where
a = fib k
fibs n = filter odd $ fibsAux n 0 []
一个是使用@hammar的建议:
fibs x = takeWhile (< x) [a | a <- [fib x | x <- [1..]], odd n]
I'm trying to filter a list that contains the Fibonacci numbers.
What I need is only odd numbers, and less or equal than N
.
This is what I have so far:
fib n | n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
fibs n = [a | a <- [fib x | x <- [1..]], odd a, a < n]
That will give me what I want, but at the same time that solution won't work because I don't know how to stop retrieving elements from fib
function. Of course, that is because of x <- [1..]
.
I have thought about two options:
- Placing a limit (that depends on
n
) inx <- [1..]
- Defining
fibs
recursive so I can know when to stop (thought about it while writing the question)
How could I do this?
I'm not looking for an efficient way
Edit:
Here are the two solutions I had at the end:
fib n | n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
fibsAux n k xs | a < n = fibsAux n (k+1) (xs ++ [a])
| otherwise = xs
where
a = fib k
fibs n = filter odd $ fibsAux n 0 []
and the one using the suggestion of @hammar:
fibs x = takeWhile (< x) [a | a <- [fib x | x <- [1..]], odd n]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看 Data.List 中的
takeWhile
函数(并由 Prelude 重新导出)。例如,请注意,即使列表是无限的,一旦找到不满足谓词的元素,该列表就会终止。
Have a look at the
takeWhile
function from Data.List (and re-exported by the Prelude). For example,Note that even though the list is infinite, this terminates once it finds an element that does not satisfy the predicate.
还有一种更有效的方法来计算斐波那契数:
可以对其进行过滤以仅给出奇数:
可以将其截断为小于或等于 N:
There's also a more efficient way to compute Fibonacci numbers:
Which can be filtered to give only the odd numbers:
Which can be truncated to less than or equal to N: