不使用zipWith的斐波那契数字 [英] Fibonacci numbers without using zipWith

查看:52
本文介绍了不使用zipWith的斐波那契数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试实现从0到n的斐波那契数列列表,而不使用懒惰的

I have been trying to implement a list of Fibonacci number sequence from 0 to n without using the lazy zipwith method. What I have so far is code that returns a list from n to 1. Is there any way I can change this code so it returns the list from 0-n at all?

示例:

fib_seq 4 = [3,2,1,1] 
-- output wanted: [1,1,2,3]

如果没有一种方法可以执行我想要的代码,有没有一种方法可以只返回斐波那契数字列表并输入一个数字再说4则它将返回 [0,1,1,2] .

If there is not a way to do what I want the code to do, is there a way to just return the list of Fibonacci numbers taking in a number say again 4 it would return [0, 1, 1, 2].

fib_seq :: Int -> [Int]
fib_seq 0 = [0]
fib_seq 1 = [1]
fib_seq n = sum (take 2 (fib_seq (n-1))) : fib_seq (n-1)

推荐答案

您可以选择实现fib编号的另一种方法是使用辅助函数,然后使用一个单独的函数,该函数将产生无限数量的fib编号,或者您可以使用10个fib,而输出的结果将是前10个fib.我的函数绝对不是用zipWith函数最终确定FIB编号的最快方法,但是您在这里没有使用它,因此这是我在没有zipWith的情况下实现它的方法.

Another way you could choose to implement the fib numbers is the use of a helper function then a function on it's own that will produce the infinite list of fib numbers, or you could use take 10 fibs and the output for this would be the first 10 fib numbers. My function is definitely not the fastest way to work out the fib numbers infintely that would be with the zipWith function, but you are not using that here so here is my way to implement it without zipWith.

例如,取10个fib 将返回: [0,1,1,2,3,5,8,13,21,34]

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)   

fibs :: [Int]
fibs = (map fib [0..])

这篇关于不使用zipWith的斐波那契数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆