13

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

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
Adam Barney
  • 2,377
  • 3
  • 18
  • 24

5 Answers5

5

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

2

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
  • 47,556
  • 6
  • 64
  • 86
  • 1
    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 Dec 16 '08 at 17:59
  • 1
    @Adam: Microsoft deliberately closed the interfaces that made this possible specifically to prevent people from using this technique to create competitors to Visual Studio. – J D Oct 29 '10 at 10:26
1

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
  • 9,976
  • 1
  • 39
  • 82
0

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.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Alex Fort
  • 18,459
  • 5
  • 42
  • 51
0

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

Agnius Vasiliauskas
  • 10,935
  • 5
  • 50
  • 70