簡體   English   中英

遞歸地添加給定N次的列表

[英]Recursively add to a list for a given N number of times

我正在嘗試創建一個給定數字和列表的函數,將給定的數字添加到列表中並減少該數字。 執行此操作直到數字達到0並返回列表。

IE“incList 5 []”應返回[5,4,3,2,1]

這是我到目前為止的代碼

incList :: Int -> [a] -> [a]
incList 0 xs = []
incList g [] = []
incList g (x:xs) = g:x ++ incList (g-1) (xs)

我使用'a'因為我​​希望列表以后包含任何內容。

我目前收到此錯誤:

    Couldn't match expected type ‘[a]’ with actual type ‘a’
  ‘a’ is a rigid type variable bound by
      the type signature for incList :: Int -> [a] -> [a]
      at incList.hs:1:12
Relevant bindings include
  xs :: [a] (bound at incList.hs:4:14)
  x :: a (bound at incList.hs:4:12)
  incList :: Int -> [a] -> [a] (bound at incList.hs:2:1)
In the first argument of ‘(++)’, namely ‘x’
In the second argument of ‘(:)’, namely ‘x ++ incList (g - 1) (xs)’

據我所知,您希望預先掛起一個列表,其中的數值從某個起始值開始倒數。 第一次嘗試時會出現幾種類型和邏輯錯誤:

incList :: Int -> [a] -> [a]

首先,你說你的初始值是一個Int ,但您的列表中包含的任何值(通過a類型變量)。 你不能有一個混合類型Inta的列表,所以你必須以某種方式統一這些。

為了清楚起見,你說“我正在使用'a'因為我​​希望這個列表后來包含任何內容。” 但這不是一個有效的選項 - 列表必須只包含一種類型,你似乎決定使用數字。

繼續,我們得到你的自定義遞歸函數。 制作你自己的很好,只要知道這可以通過內置函數或語法糖來處理。

incList 0 xs = []
incList g [] = []

你的第一個基礎案例是好的,但第二個案例是好的,而不是那么多。 你明確說incList 5 []不應該是[]而是[5,4,3,2,1]所以你如何放棄上面的第二個案例。

incList g (x:xs) = g:x ++ incList (g-1) (xs)

在這里,你為什么要x:xs原始列表( x:xs )。 我認為你想要預先掛起值,而不是取消值並將新值與舊值混合。

而且,表達式g:x ++沒有任何意義。 x不是一個列表,因此它們都不是g : x ,因此它們不會為(++) :: Int -> Int -> Int創建一個有效的參數,你可能會使用g : x : incList ...

通過這些更改,我們得出:

incList :: Int -> [Int] -> [Int]
incList 0 xs = xs
incList g xs = g : incList (g-1) xs

這與以下幾乎相同:

incList g xs = [g,g-1..1] ++ xs

閱讀起來有點清潔。

++運算符是列表連接運算符。 它的類型是[a] -> [a] -> [a] 這意味着它的輸入都是列表。 從錯誤中可以看出,您將x作為第一個輸入傳遞給++ ,而x的類型只是a

嘗試更換這個使用++: ,例如:

incList g (x:xs) = g : x : incList (g-1) (xs)

類型:a -> [a] -> [a] ,這應該在這里工作。 可能還有其他問題,我沒有檢查過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM