0

It eill work when : replace :: Eq a => a -> a -> [a] -> [a] will be. How can I convert az a to an [a] in my code ?

replace :: Eq a => a -> [a] -> [a] -> [a]
replace _ _ [] = []
replace a x (y:ys)
 | a == y = x : replace a x ys
 | otherwise = y : replace a x ys

Example:

replace '?' "a" "" == ""
replace 'a' "e" "alma" == "elme"
replace 'a' "e" "nincsbenne" == "nincsbenne"

teki2021
  • 81
  • 5

1 Answers1

3

You are using wrong operator for the first guard (a == y) - : is used to prepend a head element to a list but x is a list not a single element, so you need to use ++ which concatenates two lists (x and one returned by recursive call):

replace :: Eq a => a -> [a] -> [a] -> [a]
replace _ _ [] = []
replace a x (y:ys)
 | a == y = x ++ replace a x ys -- ++ instead of :
 | otherwise = y : replace a x ys

Related - Haskell (:) and (++) differences

Guru Stron
  • 102,774
  • 10
  • 95
  • 132