Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell replace characters in string

Tags:

haskell

Supposing I had the string "HELLO WORLD" is there a way I can call a function that replaces the character 'O' in the string with the character 'X' so that the new string would look like "HELLX WXRLD"?

like image 330
MrD Avatar asked Oct 23 '13 14:10

MrD


5 Answers

How about:

let 
    repl 'o' = 'x'
    repl  c   = c
in  map repl "Hello World"

If you need to replace additional characters later, just add clauses to the repl function.

like image 185
Ingo Avatar answered Oct 05 '22 21:10

Ingo


Sorry for picking up this old thread but why not use lambda expressions?

λ> let replaceO = map (\c -> if c=='O' then 'X'; else c)
λ> replaceO "HELLO WORLD"
"HELLX WXRLD"`
like image 25
Arnon Avatar answered Oct 05 '22 22:10

Arnon


Alternative 1 - Using MissingH

First:

import Data.List.Utils (replace)

Then use:

replace "O" "X" "HELLO WORLD"

Alternative 2 - Using Control.Monad

One funny bastard:

import Control.Monad (mfilter)

replace a b = map $ maybe b id . mfilter (/= a) . Just

Example:

λ> replace 'O' 'X' "HELLO WORLD"
"HELLX WXRLD"

Alternative 3 - Using if

Amon's suggestions was probably the finest I believe! No imports and easy to read and understand!

But to be picky - there's no need for semicolon:

replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map $ \c -> if c == a then b else c
like image 26
Leif Bork Avatar answered Oct 05 '22 21:10

Leif Bork


Here's another possible solution using divide and conquer:

replaceO [] = []
replaceO (x:xs) = 
     if x == 'O' 
     then 'X' : replaceO xs 
     else x : replaceO xs

First, you set the edge condition "replaceO [] = []".
If the list is empty, there is nothing to replace, returning an empty list.

Next, we take the string and divide it into head and tail. in this case 'H':"ELLOWORLD"
If the head is equal to 'O', it will replace it with 'X'. and apply the replaceO function to the rest of the string.
If the head is not equal to 'O', then it will put the head back where it is and apply the replaceO function to the rest of the string.

like image 28
Iceandele Avatar answered Oct 05 '22 21:10

Iceandele


If you depend on the text package (like 99.99% of Haskell applications), you can use T.replace:

>>> replace "ofo" "bar" "ofofo"
"barfo"
like image 43
Kutyel Avatar answered Oct 05 '22 21:10

Kutyel