2

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

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

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

非常感谢!

问候!

4

1 回答 1

3

正如评论中指出的那样,您不能 mutate counter,但您可以使用as 参数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

于 2013-05-08T07:19:05.950 回答