12

I have the following string "not really//" and I want to write a function that replaces every two slashes "//" with two dots ".."

I thought about using map, but then I would iterate through characters and can't know if a slash is going to be followed by another or not. Any clue how this can be done? (without regex)

3 Answers 3

15

We can use the replace :: Text -> Text -> Text -> Text function of the Data.Text function. For example:

Prelude Data.Text> replace "//" ".." "not really//"
"not really.."

Here we work however on Texts. If that is a problem, we can also use pack :: String -> Text and unpack :: Text -> String to convert between String and Text. So we can define a function with:

{-# LANGUAGE OverloadedStrings #-}

import Data.Text(pack, unpack, replace)

replacedoubleslash :: String -> String
replacedoubleslash = unpack . replace "//" ".." . pack

But usually for efficient string processing - both in terms of speed and memory - using Text is better than working with Strings.

Sign up to request clarification or add additional context in comments.

Comments

8

Explicit recursion looks fine here:

replace :: String -> String
replace ('/':'/':xs) = '.' : '.' : replace xs
replace (x:xs)       = x : replace xs
replace ""           = ""

This does not scale to long patterns, but for replacing "//" it should work fine.

Comments

0

If you don't want to use any package, this is what I've come with:

isHead':: String -> String -> String -> Bool
isHead' str [] ret = True
isHead' [] key  ret = False
isHead' (x:xs) (x':xs') ret = (x == x') && isHead' xs xs' ret

isHead:: String -> String ->  Bool
isHead  key str= isHead' str key key

remouveXelem:: Int ->[a] -> [a]
remouveXelem i a | i <= 0 = a
remouveXelem _ [] = [] 
remouveXelem i (x:xs) = remouveXelem (i - 1) xs  

replace :: String -> String -> String -> String
replace ori new [] = []
replace ori new s = if isHead ori s then
    new ++ replace ori new (remouveXelem (length ori) s)
    else head s : replace ori new (tail s)

replace "i" "a" "il etait une fois" => "al etaat une foas"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.