0

私は休暇中にハスケルに少し時間を費やしていますが、今は問題にぶつかりました。ブール値で構成されるリストがあり、整数のリストを取得して、対応する位置でブール値を反転する関数を作成しようとしています。

次のコードをGHCiにロードし、flipBits testBoard [1,0,2]を実行しようとすると、結果は[True、True、False、False]になります。これをflipBitstestBoard[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
4

2 に答える 2

2

あなたのflipBit機能で

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

反転するのは0 に達したときだけなので、board反転したいのすべての要素を に置き換えます。not (board !! 0)which

そこから1つの引数を削除したいだけです。

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
于 2012-12-23T23:46:14.827 に答える
1
    | which == 0 = (not (board !! which)):xs

ガードは、RHS はwhichが 0 の場合にのみ評価されると言っているので、これは以下と同じです。

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

boardこれが、歩き始める前の「元の」ボードです。したがって、特定の位置でビットを反転する代わりに、ビットはリストの先頭にあるビットの反転に置き換えられます。

代わりに行う必要があります

    | which == 0 = not x : xs

次に、最初のパラメーターが必要な理由を自問してくださいflipBit

于 2012-12-23T23:45:16.560 に答える