Home > Net >  Why does the following code cause a "parse error (possibly incorrent indentation or mismatched
Why does the following code cause a "parse error (possibly incorrent indentation or mismatched

Time:02-11

I'm attempting to create a replace function and the code below creates the error described in the post title in the first line of non-commented code following it. I have no idea as to why this is happening, so any help would be greatly appreciated.

 replace [] t r n = []
    replace [] _ _ _ = []
    replace xs _ _ 0 = xs
    replace (x:xs) t r n
         | x == t = r:(replace [xs] t r (n-1))
         | otherwise x (replace [xs] t r n)

CodePudding user response:

There are some problems here: all the parts of the definition should start at the same column, so you should unindent the lines after the first one. Furthermore you need to write a = after the otherwise. xs is a list, so you call replace with replace xs, not replace [xs]. For the last guard you are constructing a list, so x : (…), not x (…). The second clause also does not make much sense, since that is equivalent to the first one.

You thus can implement this as:

replace :: (Integral n, Eq a) => [a] -> a -> a -> n -> [a]
replace [] _ _ _ = []
replace xs _ _ 0 = xs
replace (x:xs) t r n
  | x == t = r : replace xs t r (n-1)
  | otherwise = x : replace xs t r n
  • Related