用' _'替换字符串中的重复字符char

时间:2016-02-11 03:46:59

标签: haskell replace

我正在编写一个Haskell函数,该函数接收一个字符串并用' _'替换字符串中的任何重复字符。到目前为止,我有这个:

markDups :: [Char] -> [Char]
markDups = dupsHelp []
where dupsHelp c [] = c
      dupsHelp c (x:xs)
          | x `elem` c = dupsHelp c xs
          | otherwise = dupsHelp (c ++ [x]) xs

代码删除重复的字符。

示例:" Hello World" - > " Helo Wrd"

我如何修改此代码以获得" Hel_o W_r_d"?谢谢。

2 个答案:

答案 0 :(得分:2)

您无需存储已经看过的角色。您可以从字符串的其余部分中删除所有出现的字符:

markDups :: [Char] -> [Char]
markDups []       = []
markDups ('_':xs) = '_' : markDups xs
markDups (x  :xs) = x   : markDups (map mark xs)
  where
    mark y = if x == y then '_' else y

答案 1 :(得分:1)

这很简单:

markDups :: [Char] -> [Char]
markDups = dupsHelp []
where dupsHelp c [] = c
      dupsHelp c (x:xs)
          | x `elem` c = dupsHelp (c ++ "_") xs
--                                ~~~~~~~~~~
          | otherwise = dupsHelp (c ++ [x]) xs

您可以放弃x并将其替换为x,而不是简单地放弃'_'

你也可以用左折来表达:

import Data.List (foldl')

markDups = reverse . snd . foldl' go ([], [])
  where
  go (seen, acc) c =
    ( c : seen          -- Add character to seen duplicates for next step.
    , if c `elem` seen  -- If character is in duplicates:
      then '_' : acc    --   Add an underscore to result.
      else c : acc      --   Otherwise, just add the character.
    )