該replaceAtMatrix函式應該接受一個元組(Int,Int),該元組決定需要更改的a值、要更改的值以及 List 中的 List 的位置[[a]]。
如果元組的值超過串列長度,則[[a]]需要回傳原始值。
replaceAtList :: Int -> a -> [a] -> [a]
replaceAtList _ _ [] = []
replaceAtList 0 a (_:xs) = a:xs
replaceAtList number a (x:xs)
| number < 0 = x:xs
| number > (length (x:xs)-1) = x:xs
| otherwise = x : replaceAtList (number-1) a xs
replaceAtMatrix :: (Int,Int) -> a -> [[a]] -> [[a]]
replaceAtMatrix _ _ [] = []
replaceAtMatrix (0,num2) a (x:xs) = replaceAtList num2 a x : xs
replaceAtMatrix (num1,num2) a (x:xs)
| num1 < 0 = x:xs
| num1 > (length (x:xs)-1) = x:xs
| num2 < 0 = x:xs
| num2 > (length (x:xs)-1) = x:xs
| otherwise = x : replaceAtMatrix (num1-1,num2) a xs
我檢查了一些測驗,它通過了大部分測驗,但是有一個測驗會無限回圈。這是有效的測驗。
replaceAtMatrix (-1,0) 'A' ["bcd","lds","rtz"] == ["bcd","lds","rtz"]
replaceAtMatrix (0,0) 'A' ["bcd","lds","rtz"] == ["Acd","lds","rtz"]
replaceAtMatrix (2,0) 'A' ["bcd","lds","rtz"] == ["bcd","lds","Atz"]
replaceAtMatrix (3,0) 'A' ["bcd","lds","rtz"] == ["bcd","lds","rtz"]
replaceAtMatrix (2,2) 'A' ["bcd","lds","rtz"] == ["bcd","lds","rtA"]
這是一個沒有的。
編輯:我剛剛意識到這可能是因為我在無限串列中使用了長度。如何在不使用長度的情況下重寫它?
take 5 (replaceAtMatrix (1,2) 100 [[1..],[1,11..],[],[12,13,14]] !! 1) == [1,11,100,31,41]
如果沒有警衛,我會得到一個不在范圍內的變數錯誤。
replaceAtList :: Int -> a -> [a] -> [a]
replaceAtList _ _ [] = []
replaceAtList 0 a (_:xs) = a:xs
replaceAtList number a (x:xs) = x : replaceAtList (number-1) a xs
replaceAtMatrix :: (Int,Int) -> a -> [[a]] -> [[a]]
replaceAtMatrix _ _ [] = []
replaceAtMatrix (0,num2) a (x:xs) = replaceAtList num2 a x : xs
replaceAtMatrix (num1,num2) a (x:xs) = x : replaceAtMatrix (num1-1,num2) a xs
uj5u.com熱心網友回復:
我認為你有你的答案,并且可以取得進展,但我認為向你展示替代實作可能會很有趣。您現有的代碼中有一些重復,將串列遍歷到特定位置,然后進行更改。這里有一個關于如何實作一次的想法:
onIndex :: Int -> (a -> a) -> ([a] -> [a])
onIndex n f = if n < 0 then id else loop n where
loop _ [] = []
loop 0 (x:xs) = f x:xs
loop n (x:xs) = x:loop (n-1) xs
這不是采用元素并替換該元素,而是采用任意編輯功能并將該功能應用于適當位置的元素。我們可以利用這個與值替換元素foo使用const foo的編輯功能。但是,這是關鍵,我們還可以使用本身呼叫的編輯功能onIndex!
replaceAtMatrix :: (Int, Int) -> a -> [[a]] -> [[a]]
replaceAtMatrix (m, n) = onIndex m . onIndex n . const
uj5u.com熱心網友回復:
不要使用length. 這將在無限串列上出錯:您不需要這個:如果number > length somelist, 最終它將到達串列的末尾:
replaceAtList :: Int -> a -> [a] -> [a]
replaceAtList _ _ [] = []
replaceAtList n _ xs
| n < 0 = xs
replaceAtList 0 a (_:xs) = a:xs
replaceAtList number a (x:xs) = x : replaceAtList (number-1) a xs
replaceAtMatrix :: (Int,Int) -> a -> [[a]] -> [[a]]
replaceAtMatrix _ _ [] = []
replaceAtMatrix (m, _) _ xs
| m < 0 = xs
replaceAtMatrix (0,num2) a (x:xs) = replaceAtList num2 a x : xs
replaceAtMatrix (num1,num2) a (x:xs) = x : replaceAtMatrix (num1-1,num2) a xs
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365064.html
標籤:哈斯克尔
