我正在尝试Haskell,我正在尝试迭代地构建一个列表。
fibList :: Int -> [Int]
fibList n = if n == 1 then [1]
else [n]:fibList (n - 1)
我的最终目标是构建一个斐波纳契数列表,但是现在我只是想构建一个整数下降列表。但是,当我尝试将此代码加载到ghci时,我收到以下错误
fibonacci.hs:9:22: error:
• Couldn't match type ‘Int’ with ‘[Int]’
Expected type: [[Int]]
Actual type: [Int]
• In the second argument of ‘(:)’, namely ‘fibList (n - 1)’
In the expression: [n] : fibList (n - 1)
In the expression: if n == 1 then [1] else [n] : fibList (n - 1)
我做错了什么?
编辑:
让它运转起来。谢谢大家!
fibList :: Int -> [Int]
fibList n = if n == 1 then [1]
else n:fibList (n - 1)
也让它成为斐波那契数字列表!
fibList :: Int -> [Int]
fibList n
| n <= 0 = error "n must be a positive integer"
| n == 1 = [1]
| n == 2 = [1, 1]
| otherwise = ( prev_term + twice_prev_term ) : prior_fib_list
where prior_fib_list = fibList (n - 1)
prev_term = prior_fib_list !! 0
twice_prev_term = prior_fib_list !! 1
答案 0 :(得分:5)
您不能将cons
数字列表添加到数字列表中。不过,您可以cons
一个数字到一个数字列表:
fun 1 = [1]
fun n = n : (fun (n - 1))
答案 1 :(得分:4)
您要做的是添加一个数字列表[n]:
到数字列表[1]
这不是cons运算符的工作原理,因为它只能将列表元素添加到该列表中,例如。
[a]
至[[a]]
或a
至[a]