我想折叠一个字符串,以便任何以@开头的零出现被替换为“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)) "" "[email protected]"
但是,它不起作用。 Foldl期待字符串列表,我提供的仅仅是一个字符串。我如何克服这一点?
我想折叠一个字符串,以便任何以@开头的零出现被替换为“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)) "" "[email protected]"
但是,它不起作用。 Foldl期待字符串列表,我提供的仅仅是一个字符串。我如何克服这一点?
以志的建议,
rep "" = ""
rep ('@' : '0' : xs) = "@k" ++ rep xs
rep (x : xs) = x : rep xs
如果我们想更大胆的尝试,
rep = snd . mapAccumL go False
where
go True '0' = (False, 'k')
go _ '@' = (True, '@')
go _ x = (False, x)
甚至
rep = snd . mapAccumL go 'x'
where
go '@' '0' = ('0', 'k')
go _ y = (y, y)
要使用第二种方法(只是因为它是更短的使用foldr
;第一个也可以正常工作,并允许泛化),
rep xs = foldr go (const "") xs 'x'
where
go '0' r '@' = 'k' : r '0'
go x r _ = x : r x
要使用zipWith
(这是比较尴尬的概括):
rep xs = zipWith go ('x' : xs) xs where
go '@' '0' = 'k'
go _ x = x
它的作品谢谢! – Andrew
正如其他人评论说,foldl
将不合身这项任务。然而,使用difference list的想法,你可能还在使用foldl
做到这一点有效:
repl :: String -> String
repl a = foldl loop id a ""
where
loop :: (String -> String) -> Char -> (String -> String)
loop f '@' ('0':rest) = f ('@':'k':rest)
loop f x xs = f (x:xs)
只是为了演示的目的,事实上,这个问题已经问了foldl
解决方案。 (不是我会推荐这样做)。
虽然这应该有正确的渐近边界,就像“构建反向,然后反向”技术一样,它在列表的脊柱中是完全严格的,因此在实践中效率低下。 – dfeuer
不要用'foldl'做到这一点。这绝对是一个'foldr'或'mapAccumL'问题。 'foldl'肯定会让这个缓慢。 – dfeuer
但是,如果我使用foldr,如何知道给定0是否在@之前。 – Andrew
为什么要使用任何折叠? – melpomene