Question

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)"
Was it helpful?

Solution

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

OTHER TIPS

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

import Text.Format
format "{0}^3 + {0} + sin({0})" ["6.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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top