[英]Writing a function to construct a list of descending natural numbers in 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.