作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想折叠一个字符串,以便 @ 前面出现的任何零都被替换为“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"
但是,它不起作用。 Foldl 需要字符串列表,而我提供的只是一个字符串。我该如何克服这个问题?
最佳答案
听取chi的建议,
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
关于haskell - 折叠在绳子上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811390/
我是一名优秀的程序员,十分优秀!