2012-12-04 47 views
1

我創造了這個數據類型和功能:zipWith哈斯克爾

type Bit = Int 

randomFloatList :: Int -> [Float] 
randomFloatList seed = randoms (mkStdGen seed) 

而且我想創建一個使用zipWith功能。該函數有一個seed作爲參數,用於randomFloatList,如果隨機元素介於0和噪聲之間,則該位被更改。我試圖這樣做,但我與困難zipWith

謝謝。

+0

我們在說什麼困難?提供更多的代碼,以便我們確定失敗的原因。 – ljedrz

回答

4

我相信你想採取一個Bit s列表,並使用隨機列表來決定是否改變原來的。 (如果沒有,請澄清。)

channel :: Int -> Float -> [Bit] -> [Bit] 
channel seed noise xs = zipWith (alterBit noise) (randomFloatList seed) xs 

注意到你並不需要一些括號 - 你不需要括號功能應用,只是進行分組。

alterBit :: Float -> Float -> Bit -> Bit 
alterBit noise random bit | random <= noise = alter bit 
          | otherwise = bit 

再次,我已經刪除,以我使用這個與列表中的任何參考 - zipWith將發送這一功能,需要進行花車和位列表的元素。

我把定義

data Bit = O | I deriving Show 

的自由,只能想到一個ALTER功能:

alter :: Bit -> Bit 
alter O = I 
alter I = O 

測試一下:

> take 6 $ randomFloatList 3 
[0.10321328,0.98988104,0.46191382,0.8553592,0.7980472,0.35561606] 

> map (<= 0.5) $ take 6 $ randomFloatList 3 
[True,False,True,False,False,True] 

> channel 3 0.5 [O,O,O,O,O,O] 
[I,O,I,O,O,I] 

是啊,這換的這應該。

0

zipWith的簽名是(a -> b -> c) -> [a] -> [b] -> [c]。這意味着將兩個參數映射到兩個列表上的函數是很有用的。

我想,你的情況,你只想映射在一個單獨的列表功能(因爲你的函數alterBit只需要一個參數),所以你不得不使用map,不zipWith

還請注意,除非你將它們定義爲您的模塊中的常量或明確地傳遞他們alterBitseednoise將不可見的alterBit

+0

你能說出爲什麼我的更新解決方案無法正常工作嗎?謝謝 – user1876106

+0

我找到了正確的解決方案。謝謝你的解釋,這很有幫助。 – user1876106