开发者

How to dump obj to xml in F#

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 开发者_如何学CCode “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 match have to return the same type of object. Your current code returns either an XElement or an Array. Since the name of the function is obj2xml, I guess that the correct type is XElement.

That means you need to wrap the array in an XElement somehow. I'm going to guess that r is short for 'root' and that since all the other XElements returned have r as their first argument, you should pass that.

| A -> o |> Array.map (fun z -> obj2xml r z)
// change to:
| A -> new XElement(r, o |> Array.map (fun z -> obj2xml r z))

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 #r compiler directives.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜