2014-11-03 60 views
0

我有一個像這樣的列表:[[0,0,0,1,0],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]],我想用[2,2,2,1,2]之類的東西替換此列表的頭部,即[0,0,0,1,0],以獲得[[2,2,2,1,2],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]。我怎樣才能做到這一點?只替換haskell中的列表頭部?

編輯:

我有這個功能,返回[[0,0,0,1,0],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]],我想它返回[[2,2,2,1,2],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]

firstfunc :: (RandomGen g) => g -> Int -> Float -> [[Int]] 
firstfunc rnd n p = makGrid $ map (\t -> if t <= p then 1 else 0) $ take (n*n) (randoms rnd) 
    where makGrid rnd = unfoldr nextRow (rnd, n) 
     nextRow (_, 0) = Nothing 
     nextRow (es, i) = let (rnd, rest) = splitAt n es in Just (rnd, (rest, i-1)) 
+0

'replaceFirst(_:xs)newHead = newHead:xs'? – bheklilr 2014-11-03 23:10:02

回答

1
change 0 = 2 
change x = x 

replace (x:rest) = map change x:rest 
+0

這種方式不起作用? – jamshidh 2014-11-03 23:31:22

+0

我們不能將它添加到上述功能嗎?我的意思是我要叫它替代還是什麼? – 2014-11-03 23:35:17

+0

你這樣做就像我在最後一個問題中展示給你的那樣....'((替換)。)。 firstfunc)',或者等價地'替換$ firstfunc gen 1 0.3'。 – jamshidh 2014-11-03 23:41:09

0

如果你想改變一個列表的頭,你可以創建一個函數的一般方法:

transformHead :: (a -> a) -> [a] -> [a] 
transformHead _ [] = [] 
transformHead f (x:xs) = (f x):xs 

,那麼你可以用它來從firstFunc例如變換的結果

transformHead (map (\x -> 2 - x)) $ firstfunc gen c p