Search code examples
stringlisthaskelltexthaskell-stack

Haskell: Replace a subString in a String without Data.List package


I'm very new in Haskell and I want to know how I can replace a predetermined word in a String by another word. This is my code so far, I know I can't do this for now:

treat :: String -> String
treat text = text

main::IO()
main = do argv <- getArgs
          texte <- readFile "intputText"
          print (separation text)
          print ( treat text )


separation :: String -> [String]
separation [] = [""]
separation (c:cs) | c == "\Graph"  = "Graphic : " : rest
                  | c == '}'  = "" : rest
                  | c == '{'  = "" : rest
                  | otherwise = (c : head rest) : tail rest
    where rest = separation cs

So basically I know I can't put a String in the first c == "\Graph" so I want to know how I can basically replace every word "\Graph" in my String text by "Graphic".

I want to be able to do that without importing any package.

If anyone can help me out I'd really appreciate it.

Thank you very much!


Solution

  • replace :: String -> String -> String-> String
    replace [] token repl = []
    replace str@(s:ss) token@(t:tx) repl
    
            -- check if first char of string equal to first char of token
            | s == t = case validateToken token str of
                    Just list -> repl ++ replace list token repl
                    Nothing -> s : replace ss token repl
    
            -- if not equal then continue recursion step
            | otherwise = s: replace ss token repl
                    where
                            -- validate if token matches the following chars of the string
                            -- returns Nothing if token is not matched
                            -- returns the remaining string after the token if token is matched
                            validateToken:: String -> String -> Maybe String
                            validateToken (a:as) [] = Nothing
                            validateToken [] list = Just list
                            validateToken (a:as) (x:xs) 
                                    | a == x = validateToken as xs 
                                    | otherwise = Nothing
    
    example = replace "yourString" "token" "new"