2012-12-23 23 views
0

我在假期中花費了一點時間在Haskell上,但現在我遇到了一個問題。我有一個由布爾值組成的列表,並且我正在試圖創建一個函數,該函數需要一個整數列表並在相應的位置翻轉布爾值。結果取決於列表的順序,即使它不應該

如果您加載下面的一段代碼到GHCI並嘗試運行flipBits測試臺[1,0,2]結果是[真,真,假,假]。如果用flipBits testBoard [1,2,0]運行它,結果是[True,True,True,False]

我想結果不依賴於傳遞給flipBits的列表中的數字順序(顯然列表中的0會停止執行)。我究竟做錯了什麼?

flipBit board which (x:xs) 
    | which == 0 = (not (board !! which)):xs 
    | otherwise = x:(flipBit board (which-1) xs) 

flipBits board [] = board 
flipBits board (x:xs) = flipBits (flipBit board x board) xs 

testBoard = take 4 $ repeat False 

回答

2

在你flipBit功能

flipBit board which (x:xs) 
    | which == 0 = (not (board !! which)):xs 
    | otherwise = x:(flipBit board (which-1) xs) 

更換了要與not (board !! 0)翻轉board的所有元素,因爲只有翻轉時which達到0

你只是想刪除一個因此,

flipBit which (x:xs) 
    | which == 0 = not x : xs 
    | otherwise = x : flipBit (which - 1) xs 

然後有

flipBits board (x:xs) = flipBits (flipBit x board) xs 

或者,因爲這是應用程序的循環模式,使用相應的高階函數,

flipBits board ixs = foldr flipBit board ixs 
+0

謝謝你,那是從我身邊一個大錯。同樣感謝你對foldr的評論,我還在開始學習摺疊,所以我很感激它。 – DkM

1
| which == 0 = (not (board !! which)):xs 

衛兵說,RHS只會當which爲0進行評估,所以這是一樣的

| which == 0 = (not (board !! 0)):xs 

board這裏是「原創」板,前我們開始沿着它走。因此,不是在某個位置翻轉該位,而是將該位替換爲列表頭部位的反轉位。

而應該做

| which == 0 = not x : xs 

,然後問自己,爲什麼你需要的第一個參數flipBit