tags:

views:

745

answers:

4

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

A: 

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.

Alex Fort
A: 

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?).

nlucaroni
Do you know if anyone has defined the grammar for F# for this purpose yet? Seems like a useful thing, and not something that should be reinvented by everyone who needs it.
Adam Barney
@Adam: Microsoft deliberately closed the interfaces that made this possible specifically to prevent people from using this technique to create competitors to Visual Studio.
Jon Harrop
+3  A: 

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ří

A: 

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.

MichaelGG