tags:

views:

881

answers:

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)"
+3  A: 

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
Dan Dyer
+1  A: 

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

jrudolph
+1  A: 

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.

squadette
@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...
Jared Updike