Replace default value with another default value Haskell

Viewed 71

I have the following code which works fine

replacePointsWithZeros :: Eq a => a -> a -> [a] -> [a]
replacePointsWithZeros _ _ [] = []
replacePointsWithZeros replacee replacer (x:xs)
   | replacee == x = replacer:replacePointsWithZeros replacee replacer xs
   | otherwise = x:replacePointsWithZeros replacee replacer xs 

but i want to replace the replacee and replacer arguments with default values, so essentially what i want is

replacePointsWithZeros :: Eq a => [a] -> [a]
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs)
   | '.' == x = '0':replacePointsWithZeros xs
   | otherwise = x:replacePointsWithZeros xs

However when I try that it complains about the types with a message I dont really understand as I am very new to Haskell. What am I doing wrong and how can i fix it?

Im assuming the issue is in the line

replacePointsWithZeros :: Eq a => [a] -> [a]

and the fact that im using a instead of Char but if I switch a to Char I get an issue with the Eq statement

1 Answers

Since you write '.' == x, this means that x is a Char, and therefore (x:xs) is a list of Chars, so a [Char], or a String.

Furthermore you write '0': and x: as output, hence that means that the output is a list of Chars as well. This thus means that the signature of replacePointsWithZeros is:

replacePointsWithZeros :: String -> String
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs)
   | '.' == x = '0':replacePointsWithZeros xs
   | otherwise = x:replacePointsWithZeros xs

You can make the above more lazy by putting the condition in a mapping function:

replacePointsWithZeros :: String -> String
replacePointsWithZeros [] = []
replacePointsWithZeros (x:xs) = f x : replacePointsWithZeros xs
    where f '.' = '0'
          f x = x

and we can use a map function instead of the explicit recursion:

replacePointsWithZeros :: String -> String
replacePointsWithZeros = map f
    where f '.' = '0'
          f x = x
Related