1
votes

I have the following function:

replace :: a -> Int -> [a] -> [a]
replace elem 0 x:xs = elem : xs
replace elem i x:xs = x ++ replace elem (i - 1) xs

And GHCi tells me that I have an illegal literal in type error, specifically on the literal 0 in the first definition. Now, I'm aware that if I'm trying to replace an arbitrary item in a list that I should not be using the list data structure. That is fine, as I am planning on refactoring my program as soon as I can get what I want to work.

As far as the compiler complaint, I'm not really sure why Haskell believes I'm trying to define a type here. Any help with this would be much appreciated.

2
Write (x:xs) instead of x:xs in the pattern and x : instead of x ++. I'm not sure why it complains about type literals - when I compile it, I get "parse error in pattern: replace" which is what I would expect.user2407038
@user2407038 your comment is an answer, so should really have been posted as such.Matthew Walton

2 Answers

3
votes

As @user2407038 mentioned there are two direct problems with your code - you mising parens and you use (++) instead of (:) - you can solve this like this:

replace :: a -> Int -> [a] -> [a]
replace elem 0 (x:xs) = elem : xs
replace elem i (x:xs) = x : replace elem (i - 1) xs

but doing so will still leave you with only a partial definition as you do not match empty lists of a s (and GHC will tell you so with a warning) - to solve this just add the missing case:

replace :: a -> Int -> [a] -> [a]
replace _    _ []     = []
replace elem 0 (x:xs) = elem : xs
replace elem i (x:xs) = x : replace elem (i - 1) xs

finally you can remove some unused bindings (variables) and rename elem (is already definied in the prelude) to make GHC even more happy (-Wall):

replace :: a -> Int -> [a] -> [a]
replace _  _ []     = []
replace el 0 (_:xs) = el : xs
replace el i (x:xs) = x : replace el (i - 1) xs
0
votes

I solved the issue by removing one empty space of indentation. I believe the compiler thought this segment of code was part of the previous (unrelated) expression. Also, I took the advice of a commenter and replaced x ++ with x :