编写一个函数以在 Haskell 中构造降序自然数列表



我正在试验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

不能将数字列表cons为数字列表。不过,您可以将数字cons到数字列表中:

fun 1 = [1]
fun n = n : (fun (n - 1))

您要做的是在前面加上一个数字列表[n]:

到数字列表[1]

这不是cons 运算符的工作方式,因为它只能在该列表中附加列表的元素,例如。

[a][[a]]

a[a]

最新更新