正如標題所示,我正在嘗試創建一個 Haskell 函式,該函式可以在串列中的某個點插入,如果我嘗試插入的點大于串列的大小,則不會插入。這是我第一次使用 Haskell,而且我才剛剛開始學習這門語言,所以我很可能遺漏了一些簡單的東西。
現在,作為我的意思的一個例子,這里是輸入及其預期輸出的例子
\> insert 3 100 [1,2,3,4,5,6,7,8]
[1,2,3,100,4,5,6,7,8]
\> insert 8 100 [1,2,3,4,5,6,7,8]
[1,2,3,4,5,6,7,8,100]
\> insert 9 100 [1,2,3,4,5,6,7,8]
[1,2,3,4,5,6,7,8]
\> insert 3 100 []
[]
這是我迄今為止嘗試過的代碼
insert 0 y [] = [y]
insert n y [] = []
insert 0 y [x:xs] = y:x:[xs]
insert n y [x:xs] = y:(insert (n-1) y [x:xs])
此代碼在第二個 xs 處插入 0 y [x:xs] = y:x:[xs]時產生以下錯誤
圖片
圖片抄本:
xs :: [a_aEmT]
Defined at C:\Users\darin\OneDrive\Desktop\Haskell\Lab1_Submit.hs:16:15
_ :: a_aEmT[sk:1]
? Couldn't match expected type ‘a’ with actual type ‘[
‘a’ is a rigid type variable bound by the inferred type of insert :: t -> a -> [[a]] -> [a] at C:\Users\darin\OneDrive\Desktop\Haskell\Lab1_Submit.hs:(14,1)-(17,45)
? In the expression: xs
In the second argument of ‘(:)’, namely ‘[xs]’
In the second argument of ‘(:)’, namely ‘x : [xs]’
? Relevant bindings include
xs :: [a]
我提前感謝您提供的任何幫助。我認為這是一個相當微不足道的問題,我只是缺乏解決它的理解。
uj5u.com熱心網友回復:
[x:xs]是具有非空串列的單例串列的模式。例如,這將匹配where is和is 。但不適用于非空串列本身:即. 此外,這還意味著如果您是串列串列的一個元素,因此如果您想使用. (x:xs)[[1,4,2]]x1xs[4,2](x:xs)xy : x : [xs]
還有一些其他錯誤:它 isy : x : xs而不是sincey : x : [xs]xs已經是一個[a]專案串列,并且在遞回的情況下,你 yield x, not y,所以:
insert :: Int -> a -> [a]
insert 0 y [] = [y]
insert n y [] = []
insert 0 y (x:xs) = y : x : xs
insert n y (x:xs) = x : (insert (n-1) y xs)
您可以將其簡化為:
insert :: Int -> a -> [a]
insert 0 y xs = y : xs
insert n y (x:xs) = x : insert (n-1) y xs
insert _ _ [] = []
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427299.html
