looping through F# record like Javascript object

荒凉一梦 提交于 2019-12-07 06:53:44

问题


In javascript, I can access every property of an object with a simple for loop as follows

var myObj = {x:1, y:2};
var i, sum=0;
for(i in myObj) sum = sum + myObj[i];

I am wondering if I can do similar thing with F#.

type MyObj = {x:int; y:int}
let myObj = {x=1; y=2}
let allValues:seq<int> = allPropertyValuesIn myObj //How do I implement allPropertyValuesIn 
let sum = allValues |> Seq.fold (+) 0

Thank you for your input

Edit to clarify why I want to do such thing
I am working on an XML file generator. The input is rows read from Database, and the xsd is predefined.

Lets say I have a "Product" Element needs to be generated and depending on the business rule, there could be 200 Children element under product some are required, some are optional. Following the advise from this excellent blog, I have had my first (very rough) design for product record:

1.    type Product{ Price:Money; Name:Name; FactoryLocation:Address option ... }
2.    let product = {Price = Money(1.5); Name = Name ("Joe Tooth Paste"); ... }
3.    let child1 = createEl ("Price", product.Price)
   ..
203.  let allChildren = child1
                        ::child2
                        ::child3
                        ..
                        ::[]
404.  let prodctEl = createElWithCildren ("Product", allChildren)

This is very tedious and un-succinct. There HAS to be a better way to do such thing in F#. I am not very kin on the reflection idea either.

Are there any other approaches or I am just doing it wrong?


回答1:


Try this:

open Microsoft.FSharp.Reflection

type MyObj = {x:int; y:int}
let myObj = {x=1; y=2}
let allValues = FSharpType.GetRecordFields (myObj.GetType())
let sum =
    allValues
    |> Seq.fold
        (fun s t -> s + int(t.GetValue(myObj).ToString()))
        0
printfn "%d" sum

However, as John Palmer admonishes, there are not very many good reasons for doing something like this.



来源:https://stackoverflow.com/questions/16976673/looping-through-f-record-like-javascript-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!