Reputation: 81
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.
Upvotes: 4
Views: 2592
Reputation: 1803
The error is in "VV" :: [Char]
but not Char
.
And "W"
is [Char]
, but not Char
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == 'W'
then 'V' : 'V' : replace t
else h : replace t
Upvotes: 0
Reputation: 54574
With pattern matching:
replace ('W':xs) = "VV" ++ replace xs
replace (x:xs) = x : replace xs
replace [] = []
With for comprehension:
replace xs = concat [if x == 'W' then "VV" else [x] | x <- xs]
With monads:
replace = (>>= (\ x -> if x == 'W' then "VV" else [x]))
With a fold:
replace = foldr (\ x -> if x == 'W' then ("VV"++) else (x:)) []
Upvotes: 4
Reputation: 74334
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"
Upvotes: 5