Writing F # code to analyze "2 + 2" in code

Extremely just begun - yesterday new to F #.

What I need: write code that analyzes the string "2 + 2" in (using the code from the training project as an example) Expr.Add (Expr.Num 2, Expr.Num 2) for evaluation. Some help at least point me in the right direction or tell me that this is too complicated for my first F # project. (This is how I learn things: beating my head off a heavy thing)

What I have: It is best to guess the code to extract the numbers. Probably terrible from the bottom. In addition, the lack of clues.

let script = "2 + 2"; let rec scriptParse xs = match xs with | [] -> (double)0 | y::ys -> (double)y let split = (script.Split([|' '|])) let fx = (split[x]) // "This code is not a function and cannot be applied." let list = [ for x in 0..script.Length -> fx ] let result = scriptParse 

Thanks.

+4
source share
1 answer

The immediate problem you are working with 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 a single list [x] , considering it a function).

Here are some more questions:

  • Your list definition is probably incorrect: x has a length up to the script , not the length of the split array. If you want to convert an array or other sequence to a list, you can simply use List.ofSeq or Seq.toList instead of explicitly understanding the list [...] .
  • Your "throws" for the two are a little strange - this is not the correct syntax for performing conversions in F #, although in this case it will work. double is a function, so brackets are not needed, and what you do really calls double 0 and double y . You should simply use 0.0 for the first case, and in the second it is not clear what you are converting from.

In general, it would probably be better to do a little more design to decide what your overall strategy will be, since it is not clear to me that you can combine a working parser based on your current approach. There are several well-known methods for writing a parser - are you trying to use a specific approach?

+2
source

Source: https://habr.com/ru/post/1369386/


All Articles