Haskell Replace characters in string with string - string

This is an extension of this question: Haskell replace characters in string
I would like to tweak the following expression to replace a char with a string
let replaceO = map (\c -> if c=='O' then 'X'; else c)
In the end, I would the following results (XX can be a string of any length):
replaceO "HELLO WORLD"
"HELLXX WXXRLD"

You can use concatMap:
let replace0 = concatMap (\c -> if c=='O' then "X" else "XX")

You kind formulate your problem in terms of traversing and accumulating based on a condition, something like this,
replace :: String -> Char -> String -> String
replace xs c s = foldr go [] xs
where go x acc = if x == c then acc ++ s
else acc ++ [x]
For you example:
>replace "HELLO WORLD" 'O' "XXX"
> "HELLXXX WXXXRLD"

Related

How to parse a string in haskell?

i m not familiar with askell.
i have to do this function parseChar :: Char -> Parser Char
> parseChar 'a' " abcd "
Just ('a', "bcd")
> parseChar 'z' " abcd "
Nothing
i did this function
type Parser r = String -> Maybe (Char, String)
parseChar :: Char -> Parser Char
parseChar x = \xs -> Just(x, xs)
i dont really understand the \ and how can I take all the string except the second.
Thanks!!
i dont really understand the \ and how can I take all the string except the second.
The \ is a lambda expression \xs -> … is a function that maps a variable xs to the … part. Here you can however move the variable to the head of the clause.
You however need to check if the first element of the string is indeed the element you are parsing:
parseChar :: Char -> Parser Char
parseChar _ "" = Nothing
parseChar x (y:ys)
| x == y = Just (y, ys)
| otherwise = Nothing
Here x is thus the char we want to parse, and "" or (y:ys) the string that we are parsing. "" means that the string is empty, in which case we return Nothing. If the string is not empty, we unpack it in the first character (head) y, and the list of remaining characters (tail) ys. In case x == y, we are thus parsing the correct character, and we can return a 2-tuple wrapped in a Just constructor. In case x is not equal to y, the parser should "fail" and return Nothing.
This then yields:
Prelude> parseChar 'a' "abcd"
Just ('a',"bcd")
Prelude> parseChar 'z' "abcd"
Nothing
Prelude> parseChar 'a' ""
Nothing

How to replace multiple characters in a string in Haskell?

I am making a program that replaces stuff using the Esperanto X-System to Esperanto, so I need it to transform "cx" to "ĉ", "sx" to "ŝ", "gx" to "g", "jx" to "ĵ", and "ux" to "ŭ", and the same for uppercase letters.
Currently it converts "a" to "b", and "c" to "d". The method I am currently using will only work for replacing single character, not multiple characters. So how do I replace multiple characters (like "cx") instead of a single one (like "a")?
replaceChar :: Char -> Char
replaceChar char = case char of
'a' -> 'b'
'c' -> 'd'
_ -> char
xSistemo :: String -> String
xSistemo = map replaceChar
So currently "cats" will transform to "dbts".
As #AJFarmar pointed out, you are probably implementing Esperanto's X-system [wiki]. Here all items that are translated are digraphs that end with x, the x is not used in esperato itself. We can for example use explicit recursion for this:
xSistemo :: String -> String
xSistemo (x:'x':xs) = replaceChar x : xSistemo xs
xSistemo (x:xs) = x : xSistemo xs
xSistemo [] = []
where we have a function replaceChar :: Char -> Char, like:
replaceChar :: Char -> Char
replaceChar 's' = 'ŝ'
-- ...
This then yields:
Prelude> xSistemo "sxi"
"\349i"
Prelude> putStrLn (xSistemo "sxi")
ŝi
A generic method:
The problem looks similar to question 48571481.
So you could try to leverage the power of Haskell regular expressions.
Borrowing from question 48571481, you can use foldl to loop thru the various partial substitutions.
This code seems to work:
-- for stackoverflow question 57548358
-- about Esperanto diacritical characters
import qualified Text.Regex as R
esperantize :: [(String,String)] -> String -> String
esperantize substList st =
let substRegex = R.subRegex
replaceAllIn = foldl (\acc (k, v) -> substRegex (R.mkRegex k) acc v)
in
replaceAllIn st substList
esperSubstList1 = [("cx","ĉ"), ("sx","ŝ"), ("jx","ĵ"), ("ux","ŭ")]
esperantize1 :: String -> String
esperantize1 = esperantize esperSubstList1 -- just bind first argument
main = do
let sta = "abcxrsxdfuxoojxii"
putStrLn $ "st.a = " ++ sta
let ste = esperantize1 sta
putStrLn $ "st.e = " ++ ste
Program output:
st.a = abcxrsxdfuxoojxii
st.e = abĉrŝdfŭooĵii
We can shorten the code, and also optimize it a little bit by keeping the Regex objects around, like this:
import qualified Text.Regex as R
esperSubstList1_raw = [("cx","ĉ"), ("sx","ŝ"), ("jx","ĵ"), ("ux","ŭ")]
-- try to "compile" the substitution list into regex things as far as possible:
esperSubstList1 = map (\(sa, se) -> (R.mkRegex sa, se)) esperSubstList1_raw
-- use 'flip' as we want the input string to be the rightmost argument for
-- currying purposes:
applySubstitutionList :: [(R.Regex,String)] -> String -> String
applySubstitutionList = flip $ foldl (\acc (re, v) -> R.subRegex re acc v)
esperantize1 :: String -> String
esperantize1 = applySubstitutionList esperSubstList1 -- just bind first argument
main = do
let sta = "abcxrsxdfuxoojxiicxtt"
putStrLn $ "st.a = " ++ sta
let ste = esperantize1 sta
putStrLn $ "st.e = " ++ ste

Palindroms & Monads

I'm new to the Haskell. I am finding following task difficult:
Enter a string of characters. Output all palindromes to the file (use the IO monad to work with the file system and input / output, use the list monad to work with the strings).`
Any code is may be helpful. Thank you in advance!
This is what I have tried so far:
palindrome :: Char -> [String]
palindrome n
| n < 0 = []
| even n = map (\front -> front ++ reverse front) fronts
| odd n = map (\front -> front ++ tail (reverse front)) fronts
where ispalindrome :: (Integral a, Show a) => a -> Bool
ispalindrome x = show x = reverse (show x)
main = do
input <- getline
putStrLn print :: IO ()
So this is basically consists of 4 things.
Read Input from the stdin
Convert input string into list of strings
From the above list find out the strings which are palindromes
print these palindromes into file.
If you convert above into functions the signatures of these will be.
String -> [String]
[String] -> [String]
Don't bother about the signature of 1st and 4th for now. These are anyways one line code readily available on internet.
2 is a single function available in Data.List called words.
3 can be again in two parts. A function which find out if a given string is palindrome. Signature will be
String -> Bool
This is also one line code.
Once you have above function the only part remaining is filtering out the strings which are palindromes in given list of strings.
isPalindrome
My haskell is a bit rusty so I don't promise the code below will work %100 yet I tried to stick to the main idea.I hope this answer helps. If you think anything is wrong both logically and syntactically, just write a comment and I will fix it asap.
isPalindrome :: [Char] -> Boolean
isPalindrome w = isPalindrome' w reverse w
where
isPalindrome' :: [Char] -> [Char] -> Boolean
isPalindrome' [] [] = true
isPalindrome' (x:xs) (y:ys) = if x == y then isPalindrome' xs ys else false
isPalindrome' _ _ = false
function above should be fine for checking for palindromes.
for writing to file part, you can create a list of palindromes first, then write all palindromes to a file in another function. so basically, first you split your string into words, then for words in given string you find palindromes, then you write the palindromes into a file.
how to read string from user?
main = do
userInput <- getLine
how to split word with delimiter?
split :: Char -> [Char] -> [[Char]]
split delimiter string = split' delimiter string [] []
where
split' :: Char -> [Char] -> [Char] -> [[Char]] -> [[Char]]
split' delim [] substr splittedStr = splittedStr if substr == [] else reverse substr ++ splittedStr
split' delim (x:xs) substr splittedStr = if x == delim then split' delim xs [] (reverse substr) ++ splittedSubstr else split' delim xs (x ++ substr) splittedSubstr
main idea is you stack characters until you see your delimeter and store them in a list when you see a delimiter.
how to filter palindromes in list?
to filter palindromes in list you use haskell's filter function as
filter isPalindrome (split ' ' userInput)
In the end, you can write a main block to run all of this in right order
main = do
userInput <- getLine
let splittedInput = split ' ' userInput
let palindromes = filter isPalindrome splittedInput
let output = concat (intersperse "\n" palindromes)
writeFile "file.txt" output

How do I replace space characters in a string with "%20"?

I wanted to write a Haskell function that takes a string, and replaces any space characters with the special code %20. For example:
sanitize "http://cs.edu/my homepage/I love spaces.html"
-- "http://cs.edu/my%20homepage/I%20love%20spaces.html"
I am thinking to use the concat function, so I can concatenates a list of lists into a plain list.
The higher-order function you are looking for is
concatMap :: (a -> [b]) -> [a] -> [b]
In your case, choosing a ~ Char, b ~ Char (and observing that String is just a type synonym for [Char]), we get
concatMap :: (Char -> String) -> String -> String
So once you write a function
escape :: Char -> String
escape ' ' = "%20"
escape c = [c]
you can lift that to work over strings by just writing
sanitize :: String -> String
sanitize = concatMap escape
Using a comprehension also works, as follows,
changer :: [Char] -> [Char]
changer xs = [ c | v <- xs , c <- if (v == ' ') then "%20" else [v] ]
changer :: [Char] -> [Char] -> [Char]
changer [] res = res
changer (x:xs) res = changer xs (res ++ (if x == ' ' then "%20" else [x]))
sanitize :: [Char] -> [Char]
sanitize xs = changer xs ""
main = print $ sanitize "http://cs.edu/my homepage/I love spaces.html"
-- "http://cs.edu/my%20homepage/I%20love%20spaces.html"
The purpose of sanitize function is to just invoke changer, which does the actual work. Now, changer recursively calls itself, till the current string is exhausted.
changer xs (res ++ (if x == ' ' then "%20" else [x]))
It takes the first character x and checks if it is equal to " ", if so gives %20, otherwise the actual character itself as a string, which we then concatenate with the accumulated string.
Note: This is may not be the optimal solution.
You can use intercalate function from Data.List module. It does an intersperse with given separator and list, then concats the result.
sanitize = intercalate "%20" . words
or using pattern matching :
sanitize [] = []
sanitize (x:xs) = go x xs
where go ' ' [] = "%20"
go y [] = [y]
go ' ' (x:xs) = '%':'2':'0': go x xs
go y (x:xs) = y: go x xs
Another expression of Shanth's pattern-matching approach:
sanitize = foldr go []
where
go ' ' r = '%':'2':'0':r
go c r = c:r

Haskell replace characters in string

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"?
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.
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"`
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
If you depend on the text package (like 99.99% of Haskell applications), you can use T.replace:
>>> replace "ofo" "bar" "ofofo"
"barfo"
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.
replace :: Char -> Char -> String -> String
replace _ _ [] = []
replace a b (x : xs)
| x == a = [b] ++ replace a b xs
| otherwise = [x] ++ replace a b xs
I'm new to Haskell and I've tried to make it simpler for others like me.
I guess this could be useful.
main = print $ charRemap "Hello WOrld" ['O','o'] ['X','x']
charRemap :: [Char] -> [Char] -> [Char] -> [Char]
charRemap [] _ _ = []
charRemap (w:word) mapFrom mapTo =
if snd state
then mapTo !! fst state : charRemap word mapFrom mapTo
else w : charRemap word mapFrom mapTo
where
state = hasChar w mapFrom 0
hasChar :: Char -> [Char] -> Int -> (Int,Bool)
hasChar _ [] _ = (0,False)
hasChar c (x:xs) i | c == x = (i,True)
| otherwise = hasChar c xs (i+1)

Resources