3

Theres is a little problem I want to solve with Haskell: let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:

subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
--          "6.2^3 + 6.2 + sin(6.2)"

4 Answers 4

6

You could use the Text.Regex package.

Your example might look something like this:

import Text.Regex(mkRegex, subRegex)

subs :: String -> String -> String -> String
subs wildcard input value = subRegex (mkRegex wildcard) input value
Sign up to request clarification or add additional context in comments.

Comments

2

See http://bluebones.net/2007/01/replace-in-haskell/ for an example which looks exactly as the piece of code you are looking for.

Comments

2

You can use text-format-simple library for such cases:

import Text.Format
format "{0}^3 + {0} + sin({0})" ["6.2"]

Comments

1

Use regular expressions (Text.Regex.Posix) and search-replace for /\Wx\W/ (Perl notation). Simply replacing x to 6.2 will bring you trouble with x + quux.

Haskell Regex Replace for more information (I think this should be imported to SO.

For extra hard-core you could parse your expression as AST and do the replacement on that level.

1 Comment

@paullrulan: I hope you aren't trying to do symbolic math WITHOUT a proper parser/AST. Strings are a nightmare for that... Please tell me you are not trying to substitute variables lexically instead of with an AST...

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.