gpt4 book ai didi

list - Haskell - 增量失败

转载 作者:行者123 更新时间:2023-12-04 04:58:39 24 4
gpt4 key购买 nike

我在这段代码中增加一个计数器时遇到了很大的麻烦。它不会增加。
编辑:它现在工作正常!

你能告诉我问题出在哪里,我该如何解决?

replaceBasedIdx    ::  String  ->  [String]  ->  String  ->  String
replaceBasedIdx findStr replaceStrList myText = replaceBasedIdxSub findStr replaceStrList myText 0

replaceBasedIdxSub :: String -> [String] -> String -> Int -> String
replaceBasedIdxSub findStr replaceStrList myText counter = loop myText 0
where
loop [] _ = []
loop myText counter =
let (prefix, rest) = splitAt n myText
in
if findStr == prefix -- found an occurrence?
then (replaceStrList !! counter) ++ loop rest (counter+1) -- yes: replace it

else head myText : loop (tail myText) counter -- no: keep looking
n = length findStr

在这段代码中增量工作得很好

为什么会这样?
numStack :: [Integer]
numStack = [20, 45, 150, 85, 19, 31, 50, 74, 57]

sumStack :: Integer
sumStack = sumStackSub 0

sumStackSub :: Int -> Integer
sumStackSub counter = if (counter < (length numStack)) then
sumStackSub (counter + 1) + (numStack !! counter)
else
0 -- dummy value

非常感谢!

问候!

最佳答案

正如评论中指出的,你不能改变 counter ,但您可以调用loop递增值为 counter作为参数:

replaceBasedIdx    ::  String  ->  [String]  ->  String  ->  String
replaceBasedIdx findStr replaceStrList myText = replaceBasedIdxSub findStr replaceStrList myText 0

replaceBasedIdxSub :: String -> [String] -> String -> Int -> String
replaceBasedIdxSub findStr replaceStrList myText counter = loop myText counter
where
loop [] _ = []
loop myText c =
let (prefix, rest) = splitAt n myText
in
if findStr == prefix -- found an occurrence?
then (replaceStrList !! (counter+1)) ++ loop rest (counter+1) -- yes: replace it

else head myText : loop (tail myText) (counter+1) -- no: keep looking
n = length findStr

您的第二个示例有效,因为您就是这样做的,因此您传递了一个递增的值 counter到被调用函数 sumStackSub .

关于list - Haskell - 增量失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16432574/

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