Replacing a string in Haskell

haskell, replace, string

Solution

It's worth being explicit about what `String` actually is. For instance, you're looking for the test case:

replace ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
==
['H', 'E', 'L', 'L', 'O', ' ', 'V', 'V', 'O', 'R', 'L', 'D']

Now, when you pattern match on a list like this the head of the list will be the first character of the string

> case "Hello world" of (c:rest) -> print c
'H'

So we can't match it with a string literal like `"W"`. In a similar way, we can't use cons (`(:)`) to prepend a string to another string, we can only add a single character!

> 'P' : "hello"
"Phello"

Instead, we'll use `(++) :: String -> String -> String` to append two strings.

replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
    if h == 'W'
      then "VV" ++ replace t
      else h : replace t

Which ought to work as expected

> replace "Hello World"
"Hello VVorld"

Problem

I'm trying to replace a string with another string in Haskell. Here's the code that I have so far, but it doesn't exactly work. ``` replace :: [Char] -> [Char] replace [] = [] replace (h:t) = if h == "W" then "VV" : replace t else h : replace t ``` I want to be able to accomplish this for example: if the string is "HELLO WORLD", the result should be "HELLO VVORLD". I think words/unwords would be helpful, but not exactly sure how to implement it.

Original source