I try to tanslate a C# code to F#.
But faild.
Here is the C# code from a bolgpost called LINQ Reduces Line Counts and Makes Code “Pop”
It’s about FP.
I translate it to
#r "System.Core.dll"
#r "System.Xml.Linq.dll"
open System
open System.Reflection
open System.Collections
open System.Collections.Generic
open System.Xml.Linq
let (|V|S|A|O|) o =
if o.GetType().IsValueType then V
elif o.GetType()=typeof<string> then S
elif o.GetType().IsArray then A
else O
let rec obj2xml r o =
match o with
| V | S -> new XElement(r, o)
| A -> o |> Array.map (fun z -> obj2xml r z)
| O -> new XElement(r, o.GetType().GetProperties() |> Array.map (fun z -> obj2xml (z.Name) (z.GetValue(o, null))))
| V | S -> new XElement(r, o) return a XElement
| A -> o |> Array.map (fun z -> obj2xml r z) return a Array
I couldn’t figure it out!
I haven’t got it complied yet!
Help me please!
The reason it won’t compile is that all branches of
matchhave to return the same type of object. Your current code returns either anXElementor anArray. Since the name of the function isobj2xml, I guess that the correct type isXElement.That means you need to wrap the array in an
XElementsomehow. I’m going to guess thatris short for ‘root’ and that since all the other XElements returned haveras their first argument, you should pass that.By the way, I don’t know if you’re using Visual Studio to write this code. If you are, then you probably want to specify your references via the project system rather than
#rcompiler directives.