> problem = replaceBasedIdx "X" ["b","d","f"] "aXcXeXgX"
> -- "abcdefg*** Exception: Prelude.(!!): index too large
This problem occurs because you never check if 'counter' is a valid
index in the 'replaceStrList'. You can solve it by not using the !!
operator at all. The solution is to also pass 'replaceStrList' in the
recursion. That way you can check whether you have exhausted all
strings in that list and as a bonus you do not need your counter
anymore:
> replaceBasedIdx :: String -> [String] -> String -> String
> replaceBasedIdx findStr replaceStrList myText = loop replaceStrList myText
> where
> loop :: [String] -> String -> String
> loop rs [] = []
> -- Check for empty list of replacements
> loop [] text = text
> -- Pattern match on the list of replacements to get both the
> -- entire list rs, the first element r and the tail rs'.
> loop rs@(r:rs') text =
> let (prefix, rest) = splitAt n text
> in if findStr == prefix
> then r ++ loop rs' rest
> else head text : loop rs (tail text)
>
> n :: Int
> n = length findStr