Parse String to Function

How to make this code work?

#pkg> add InverseLaplace

using InverseLaplace
import InverseLaplace: talbot

f2(s) = s / (s^2 + 1);
ft2 = Talbot(f2, 80);
ft2(pi / 2) #corret

f1(s) = Symbol("s / (s^2 + 1)")
ft1 = Talbot(f1, 80);
ft1(pi / 2) #error MethodError: no method matching *(::Float64, ::Symbol)

You can use this:

using InverseLaplace
import InverseLaplace: talbot

f1 = eval(Meta.parse("f1(s) = s / (s^2 + 1)")) 
ft1 = Talbot(f1, 80);
ft1(pi / 2) 

To add a little bit more info. Meta.parse will ‚Äúparse‚ÄĚ the string to an expression. Then eval will evaluate the expression, basically ‚Äúchecking the value of the expression‚ÄĚ (maybe this makes it more clear). I moved the f1(s) within the string as it should be part of the expression.

There is a discussion here about whether you should use expression parsing.

1 Like