1

I want to replace part of a string using haskell. For example I have a string "LP FACTOR PLUS FACTOR RP MULT FACTOR" and I want to replace "FACTOR PLUS FACTOR" with "TERM" so my new string will be "LP TERM RP MULT FACTOR"

any help would be appreciated.

2

2 Answers 2

3

Sometimes you just can't beat the old regular expression substitute....

> subRegex (mkRegex "FACTOR PLUS FACTOR") "LP FACTOR PLUS FACTOR RP MULT FACTOR" "TERM"
"LP TERM RP MULT FACTOR"

(Don't forget to import Text.Regex)

I can't help but notice that you are doing something that looks more like a context free grammar production however.... String substitutions will only get you so far with this, and you will probably find that you need to move onto an actual parser.

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

2 Comments

Yes I understand. However I just want to reduce the string until it becomes an "EXPR" and print out Except or Reject.
For simple problems this will work (try it, if it does what you want, by all means you've solved the problem). For a moderate sized grammar, even with a small input, you will start hitting ambiguity, and have to substitute and backtrack. The time to process input will grow exponentially with size, and suddenly ....bam.... the time to process your data shoots up to hours (ie- it will look like your program is frozen). An appropriate parser could have the same thing done in less than a second.
2

Probably not a flexible way to do so:

mkToken = words

repl :: [String] -> [String]
repl ("FACTOR":"PLUS":"FACTOR":xs) = "TERM" : xs
repl (x:xs) = x : repl xs
repl _ = []

input = "LP FACTOR PLUS FACTOR RP MULT FACTOR"

main = print $ unwords $ repl $ mkToken input

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.