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
splitis an array of strings. To access an element of this array, the syntax issplit.[x], notsplit[x](which would applysplitto the singleton list[x], assuming it were a function).Here are a few other issues:
listis probably wrong:xranges 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.ofSeqorSeq.toListinstead of an explicit list comprehension[...].doubleis a function, so the parentheses are unnecessary and what you are doing is really callingdouble 0anddouble y. You should just use0.0for 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?