2012-10-08 72 views
1

名單,我有以下功能:哈斯克爾 - 功能與涉及也許不工作

-- xs: list to be changed 
-- ws: list of indices where the values will change to 0 
replaceAtIndices xs ws = [if (fromJust (elemIndex x xs)) `elem` ws then 0 else x | x <- xs] 

功能發生在2名列表。 WS是我想改變爲0

出於某種原因,在XS值的指標,它適用於某些情況下,而不是爲別人:

*Main> replaceAtIndices [1,2,3,4] [2,3] 

[1,2,0, 0] - 正確

*Main> replaceAtIndices [1,2,3,4] [2] 

[1,2,0,4] - 正確

*Main> replaceAtIndices [1,1,2,1,3] [3] 

[1,1,2,1,3] - 應該是[1,1 ,2,0,3]

任何人都可以請解釋爲什麼這是?

在此先感謝!

+0

我編輯的標題,因爲這個問題已經無關單子接口; '也許'只是一種數據類型。 –

回答

4

elemIndex返回第一出現在列表中的項目的指標,因此,在第三種情況下它總是爲1指數不匹配3所以沒有被替換返回0

指標與項目相關聯的一個更好的辦法是使用zip

replaceAtIndices xs ws = [if i `elem` ws then 0 else x | (i, x) <- zip [0..] xs] 
+0

謝謝!這也擺脫了必須使用Monads! – user1670032