折叠在字符串上

And*_*rew 3 haskell fold

我想折叠一个字符串,以便在@之前出现的任何零都被替换为"k".所以"a.@ 0.1.2.0"变成"a.@ k.1.2.0".我怎么做?到目前为止,我的尝试是

test = foldl(\x acc-> if((last acc) == "@" && x == "0" then acc ++ "k" else acc ++ x)) "" "a.@0.1.2.0"
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用.Foldl期待字符串列表,我提供的只是一个字符串.我该如何克服这个问题?

dfe*_*uer 8

听取chi的建议,

rep "" = ""
rep ('@' : '0' : xs) = "@k" ++ rep xs
rep (x : xs) = x : rep xs
Run Code Online (Sandbox Code Playgroud)

如果我们想变得更加漂亮,

rep = snd . mapAccumL go False
  where
    go True '0' = (False, 'k')
    go _ '@' = (True, '@')
    go _ x = (False, x)
Run Code Online (Sandbox Code Playgroud)

甚至

rep = snd . mapAccumL go 'x'
  where
    go '@' '0' = ('0', 'k')
    go _ y = (y, y)
Run Code Online (Sandbox Code Playgroud)

使用foldr第二种方法(仅因为它更短;第一种方法也可以正常工作,并允许泛化),

rep xs = foldr go (const "") xs 'x'
  where
    go '0' r '@' = 'k' : r '0'
    go x r _ = x : r x
Run Code Online (Sandbox Code Playgroud)

使用zipWith(这更难以概括):

rep xs = zipWith go ('x' : xs) xs where
  go '@' '0' = 'k'
  go _ x = x
Run Code Online (Sandbox Code Playgroud)