Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a substring from a string in Haskell

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)

like image 773
J. Doe Avatar asked Jan 28 '18 22:01

J. Doe


People also ask

How do you replace a substring?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).

How do you replace a character in a string Haskell?

First, you set the edge condition "replaceO [] = []" . If the list is empty, there is nothing to replace, returning an empty list. If the head is equal to 'O', it will replace it with 'X'. and apply the replaceO function to the rest of the string.


2 Answers

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.

like image 85
Willem Van Onsem Avatar answered Oct 15 '22 15:10

Willem Van Onsem


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.

like image 23
chi Avatar answered Oct 15 '22 14:10

chi