在构建过程中从内部引用记录 [英] Reference a record from within itself during construction

查看:50
本文介绍了在构建过程中从内部引用记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一条记录,该记录使用同一构造函数中的先前定义的字段之一来计算另一个字段的值.例如

I am trying to create a record which uses one of the previously defined fields to calculate the value of another, within the same constructor. e.g.

myRecordType = {Foo:int; Bar:int[]}

myRecord = {Foo = 5;
            Bar = Array.init Foo (fun i -> i)}

当我尝试此操作时,它不会将 Foo 识别为已经存在.我也无法使用 myRecord.Foo 引用 Foo ,但这是有道理的,因为尚未构建 myRecord .但是我本以为 Foo Bar 属于同一范围,所以 Bar 可以访问 Foo ,但显然不是.

When I try this it doesn't recognise Foo as already existing. I also can't reference Foo using myRecord.Foo, but that makes sense since myRecord hasn't been constructed yet. However I would've thought that Foo and Bar would be in the same scope, so Bar could access Foo, but apparently not.

Bar 数组的大小取决于 Foo 的值,那么如何设置这种格式的记录呢?

The size of the Bar array depends on the value of Foo, so how is it possible to set up a record of this format?

推荐答案

您不能引用其他字段,甚至不应该将字段评估的顺序视为理所当然.

You cannot reference other fields, you shouldn't even take for granted the order of fields evaluation.

您可以通过其他let绑定来做到这一点:

You can do it by additional let binding:

let myrecord = 
    let calcedFoo = 5
    { Foo = calcedFoo; Bar = Array.init calcedFoo id }

您可以将记录构造表达式视为一个函数,其中赋值的右侧是传递给该函数的参数.

You can think of record construction expression as a function where right sides of assignments are parameters passed to that function.

这篇关于在构建过程中从内部引用记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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