Skip to content

Instantly share code, notes, and snippets.

@paolino
Last active February 24, 2024 20:46
Show Gist options
  • Save paolino/1659c2d056c96422223e0c0588acf0ea to your computer and use it in GitHub Desktop.
Save paolino/1659c2d056c96422223e0c0588acf0ea to your computer and use it in GitHub Desktop.
replace all occurencies of a string
import Data.List (tails)
import Data.List.NonEmpty (NonEmpty, toList)
import Prelude
import qualified Data.List.NonEmpty as NE
type Tries = [NonEmpty Char]
tries :: String -> Tries
tries [] = []
tries xs = fmap NE.fromList $ init $ tails xs
match :: String -> String -> Bool
match (x : xs) (y : ys) = x == y && match xs ys
match [] _ = True
match _ _ = False
matching :: String -> String -> Tries -> String
matching _pattern _replace [] = []
matching pattern' replacement (x : xs)
| pattern' `match` toList x =
error "TODO"
| otherwise =
error "TODO"
where
lp = length pattern' - 1
replace :: String -> String -> String -> String
replace pattern' replace' = matching pattern' replace' . tries
--- Tests ---
spec :: (Show a, Eq a) => a -> a -> IO ()
spec x y
| x == y = pure ()
| otherwise =
error
$ "Assertion failed: " <> show x <> " == " <> show y
test :: IO ()
test = do
spec
do replace "foo" "bar" "foo"
do "bar"
spec
do replace "foo" "bar" "foobar"
do "barbar"
spec
do replace "foo" "bar" "foofoo"
do "barbar"
spec
do replace "foo" "bar" "barfoo"
do "barbar"
spec
do replace "foo" "bar" "barbar"
do "barbar"
spec
do replace "foo" "bar" "bar"
do "bar"
spec
do replace "foo" "bar" "baz"
do "baz"
spec
do replace "foo" "bar" "fook"
do "bark"
spec
do replace "foo" "bar" "fof"
do "fof"
spec
do replace "foo" "bar" "ffoo"
do "fbar"
spec
do replace "foo" "bar" "ffofoo"
do "ffobar"
spec
do replace "foo" "bar" "barfoobar"
do "barbarbar"
-- -- are we really good ?
spec
do take 6 (replace "foo" "bar" $ cycle "ffofoo")
do "ffobar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment