Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a record from within itself during construction

Tags:

record

f#

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)}

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.

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?

like image 345
Magg G. Avatar asked Jul 02 '26 10:07

Magg G.


1 Answers

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

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.

like image 53
Bartek Kobyłecki Avatar answered Jul 05 '26 17:07

Bartek Kobyłecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!