gpt4 book ai didi

haskell - 折叠在绳子上

转载 作者:行者123 更新时间:2023-12-02 13:09:29 24 4
gpt4 key购买 nike

我想折叠一个字符串,以便 @ 前面出现的任何零都被替换为“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com