Writing F# code to parse "2 + 2" into code
Extremely just-started-yesterday new to F#.
What I want: To write code that parses the string "2 + 2" into (using as an example code from the tutorial project) Expr.Add(Expr.Num 2, Expr.Num 2) for evaluation. Some help to at least point me in the right direction or tell me it's too complex for my first F# project. (This is how I learn things: By bashing my head against stuff that's hard)
What I have: My best guess at code to extract the numbers. Probably horribly off base. Also, a lack of clue.
let script = "2 + 2";
let rec scriptParse xs =
match xs with
| [] -> (double)0
| y::ys -> (double)y
let split = (script.Split([|' '|]))
let f x = (split[x]) // "This code is not a function and cannot be applied."
let list = [ for x in 0开发者_运维知识库..script.Length -> f x ]
let result = scriptParse
Thanks.
The immediate issue that you're running into is that split
is an array of strings. To access an element of this array, the syntax is split.[x]
, not split[x]
(which would apply split
to the singleton list [x]
, assuming it were a function).
Here are a few other issues:
- Your definition of
list
is probably wrong:x
ranges up to the length ofscript
, not the length of the arraysplit
. If you want to convert an array or other sequence to a list you can just useList.ofSeq
orSeq.toList
instead of an explicit list comprehension[...]
. - Your "casts" to double are a bit odd - that's not the right syntax for performing conversions in F#, although it will work in this case.
double
is a function, so the parentheses are unnecessary and what you are doing is really callingdouble 0
anddouble y
. You should just use0.0
for the first case, and in the second case, it's unclear what you are converting from.
In general, it would probably be better to do a bit more design up front to decide what your overall strategy will be, since it's not clear to me that you'll be able to piece together a working parser based on your current approach. There are several well known techniques for writing a parser - are you trying to use a particular approach?
精彩评论