Haskell: 在没有Data.List包的String中替换一个子String
Haskell: Replace a subString in a String without Data.List package
我是 Haskell 的新手,我想知道如何用另一个词替换字符串中的预定词。到目前为止,这是我的代码,我知道我现在不能这样做:
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
所以基本上我知道我不能把字符串放在第一个 c == "\Graph" 所以我想知道
我如何基本上用“Graphic”替换字符串 text 中的每个单词“\Graph”。
我希望能够在不导入任何包的情况下做到这一点。
如果有人能帮助我,我将不胜感激。
非常感谢!
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"
我是 Haskell 的新手,我想知道如何用另一个词替换字符串中的预定词。到目前为止,这是我的代码,我知道我现在不能这样做:
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
所以基本上我知道我不能把字符串放在第一个 c == "\Graph" 所以我想知道 我如何基本上用“Graphic”替换字符串 text 中的每个单词“\Graph”。
我希望能够在不导入任何包的情况下做到这一点。
如果有人能帮助我,我将不胜感激。
非常感谢!
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"