How can evaluate an expression stored as a string

2019-01-15 00:15发布

I want to do something sort of like this:

let x = 5
let y = 10

let expr = Console.ReadLine()

expr

Where one might type "x+y" in the console to store in expr.

How does one evaluate a statement like this in F#?

Ultimately, I want a user to be able to enter expressions, or a set of rules for a system, on a webpage and have them saved in a database to be applied at appropriate times in an F# library. I just don't know how to convert the entered string in to a function value in F#.

Thanks for any help you may provide!

Adam

标签: .net f#
5条回答
姐就是有狂的资本
2楼-- · 2019-01-15 00:36

Or you can look at my F# code which implements math expressions evaluator.

查看更多
beautiful°
3楼-- · 2019-01-15 00:38

There's nothing out of the box for this.

I'm not sure what your needs are, but you might consider the Dynamic LINQ sample. It has a little parser to generate expression trees, which you can then compile or manipulate. ScottGu talks about it here.

While it looks like it is mainly for extending LINQ queries, it acts as a nice parser. We hacked it up to support do/let bindings for a bit more flexibility.

查看更多
Ridiculous、
4楼-- · 2019-01-15 00:41

I just saw Joh use quotation evaluations on his F# for game development page

      open Microsoft.FSharp.Linq.QuotationEvaluation
      ...
      let mk_gravity scale_func (up: 'Vec): 'Vec =
      let q = <@ let (*) = %scale_func in -9.81 * up @>
      q.Eval()

Alternately, if you are after simple math evaluation, you can download Edmonodo's Expression parser and evaluator from his codeplex plage - Symbolic Differentiation in C#/F#

Good luck - Jiří

查看更多
Evening l夕情丶
5楼-- · 2019-01-15 00:43

F# doesn't have an eval function like Lisp's (AFAIK), if that's what you're wondering. You could build up an expression tree yourself though, based on string input.

查看更多
小情绪 Triste *
6楼-- · 2019-01-15 00:54

F# doesn't have eval, as mentioned, but if you can define the grammar, you can utilize the Lex and Yacc implementations in F# (fslex and and fsyacc).

EDIT:

As a quick follow up, I know in ocaml you can exploit the interactive console to your users with ocamlmktop. I am unsure of an equivalent in F#. This, although, doesn't seem to match what you want with a web interface (correct?).

查看更多
登录 后发表回答