像Javascript对象一样遍历F#记录 [英] looping through F# record like Javascript object

查看:34
本文介绍了像Javascript对象一样遍历F#记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,我可以通过以下简单的for循环访问对象的每个属性

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];

我想知道我是否可以用F#做类似的事情.

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

谢谢您的输入

编辑以阐明我为什么要这样做
我正在研究XML文件生成器.输入是从数据库读取的行,并且xsd是预定义的.

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.

让我们说我有一个产品"元素需要生成,根据业务规则,产品下可能有200个子元素,其中一些是必需的,有些是可选的.遵循这个出色的博客的建议,我进行了第一个(非常粗糙的)设计产品记录:

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)

这是非常乏味且不简洁的.有一种更好的方法可以在F#中执行此操作.我也不很喜欢反思的想法.

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?

推荐答案

尝试一下:

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

但是,正如约翰·帕尔默(John Palmer)所告诫的那样,做这样的事情的理由并不多.

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

这篇关于像Javascript对象一样遍历F#记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆