J Cooper
J Cooper

Reputation: 17051

Constructing an F# record via positional arguments

Is it possible to take a record like:

type Foo = {
  Bar: int
  Baz: double
}

And construct it like a function call? (Perhaps let foo = Foo 3 4.5, but that doesn't seem to work.)

Right now to get that functionality I'm doing

let createFoo bar baz = { Bar = bar; Baz = baz }

But I want to make sure I'm not missing something.

Thanks, and sorry if this has been asked before!

Upvotes: 2

Views: 201

Answers (4)

Stephen Swensen
Stephen Swensen

Reputation: 22297

Not mentioned yet is that you can add a method to a record type like

type Foo = {
  Bar: int
  Baz: double
}
with
    static member create bar baz =
        {Bar=bar; Baz=baz}

And then use it like

let foo = Foo.create 3 4.5

(so you do have to work for the syntax, but it is kept well-organized as part of the type).

Upvotes: 4

Tomas Petricek
Tomas Petricek

Reputation: 243041

As already mentioned, records can be only created using record construction syntax. Another alternative to using records (other than class mentioned by Brian) is to use a discriminated union with a single case.

This way, type declaration and value construction is just a single line:

type Foo = Foo of int * float

// Create value of 'Foo'
let value = Foo(42, 4.2)

// Decompose value into int and float in a function call
let add (Foo(n, f)) = 
  (float n) + f

This way of declaring type is quite simple, so it works nice when writing code interactively. For a public API that's used from C#, class is definitely a better choice.

Upvotes: 2

Brian
Brian

Reputation: 118865

No.

Note that there is a great thing called a "class" with a thing called a "constructor" that seems like it may be appropriate for your scenario. :)

Alternatively, you can always define a function

let mkFoo x y = { Bar=x; Baz=y }

Upvotes: 1

John Palmer
John Palmer

Reputation: 25516

I don't think this is possible - my guess as to why would be what happens if you have

type Foo = {
  Bar: int
  Baz: int
}

Then how does the compiler know which element goes where.

Upvotes: 0

Related Questions