2011-03-13 124 views
6

如何刪除字符串的每個第n個元素?刪除字符串中的每個第n個元素

我猜你會以某種方式使用drop函數。

像這樣滴第一個n,你怎麼能改變這個,所以只有第n個,然後是第n個,等等,而不是所有的?

dropthem n xs = drop n xs 

回答

2
remove_every_nth :: Int -> [a] -> [a] 
remove_every_nth n = foldr step [] . zip [1..] 
    where step (i,x) acc = if (i `mod` n) == 0 then acc else x:acc

這裏的功能是什麼:

zip [1..]用於索引的所有項目在列表中,因此如zip [1..] "foo"變成[(1,'f'), (2,'o'), (3,'o')]

然後使用right fold處理索引列表,該索引列表累積索引不能被n整除的每個元素。

這是一個稍微長一點的版本,它基本上做了同樣的事情,但是避免了來自zip [1..]的額外內存分配,並且不需要計算模量。

remove_every_nth :: Int -> [a] -> [a] 
remove_every_nth = recur 1 
    where recur _ _ []  = [] 
      recur i n (x:xs) = if i == n 
      then recur 1 n xs 
      else x:recur (i+1) n xs
+0

而不是'zip'和'mod'這是稍貴,爲什麼不使用'cycle' [ 1..n]並與1比較? – Peaker 2011-03-13 12:41:32

+0

'remove_every_nth n = map snd。過濾器((/ = 0)。(\'mod \'n).fst)。 zip [1 ..]' – Alvivi 2011-03-13 12:48:20

+0

@Peaker:謝謝你的建議。我不確定如何在不使用'zip'的情況下利用'cycle',但我以不同的方式提高了效率。 – shang 2011-03-13 12:48:37

2

嘗試結合takedrop來實現此目的。

take 3 "hello world" = "hel" 
drop 4 "hello world" = "o world" 
+0

我做了我的帖子中的錯誤,我有現在這個樣子,並且它會從我的列表中的第n個值。我想從列表中刪除每一個第n個值,所以即時猜測我需要添加一些遞歸?或過濾? – Lunar 2011-03-13 11:30:14

+0

@Lunar,「每第n個值」是什麼意思? – luqui 2011-03-13 11:50:40

+0

如: 4「thisiscool」將給予「thiiscol」 其去除,每4從字符串 – Lunar 2011-03-13 11:51:40

4
-- groups is a pretty useful function on its own! 
groups :: Int -> [a] -> [[a]] 
groups n = map (take n) . takeWhile (not . null) . iterate (drop n) 

removeEveryNth :: Int -> [a] -> [a] 
removeEveryNth n = concatMap (take (n-1)) . groups n 
7

簡單。取(n-1)個元素,然後跳過1,沖洗並重復。

dropEvery _ [] = [] 
dropEvery n xs = take (n-1) xs ++ dropEvery n (drop n xs) 

或者在節目樣式效率的緣故

dropEvery n xs = dropEvery' n xs $ [] 
    where dropEvery' n [] = id 
      dropEvery' n xs = (take (n-1) xs ++) . dropEvery n (drop n xs) 
1

我喜歡以下解決方案:

del_every_nth :: Int -> [a] -> [a]  
del_every_nth n = concat . map init . group n 

你只需要定義一個函數group哪些羣體在長的部分名單ñ。但是,這是很容易的:

group :: Int -> [a] -> [[a]] 
group n [] = [] 
group n xs = take n xs : group n (drop n xs) 
+0

hlint will suggest使用'concatMap'而不是'concat。 map' – 2011-03-15 22:46:30

相關問題