Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string in Haskell

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.

like image 311
user3247171 Avatar asked Jan 12 '23 08:01

user3247171


2 Answers

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"
like image 114
J. Abrahamson Avatar answered Jan 13 '23 21:01

J. Abrahamson


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:)) []
like image 43
Landei Avatar answered Jan 13 '23 21:01

Landei