Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument validation in F# struct constructor

Here is a trivial C# struct that does some validation on the ctor argument:

public struct Foo
{
    public string Name { get; private set; }

    public Foo(string name)
        : this()
    {
        Contract.Requires<ArgumentException>(name.StartsWith("A"));
        Name = name;
    }
}

I've managed to translate this into an F# class:

type Foo(name : string) = 
    do 
        Contract.Requires<ArgumentException> (name.StartsWith "A")
    member x.Name = name

However, I can't translate this to a structure in F#:

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = { do Contract.Requires<ArgumentException> (name.StartsWith "A"); Name = name }

This gives compile errors:

Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq { ... }'

This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor.

I've had a look at this and this but they do not cover argument validation.

Where am I doing wrong?

like image 514
Akash Avatar asked Sep 26 '12 11:09

Akash


1 Answers

You can use then block after initializing structs. It is described for classes in your first link in section Executing Side Effects in Constructors, but it works for structs as well.

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = { Name = name } 
                         then if name.StartsWith("A") then failwith "Haiz"

UPDATE:

Another way closer to your example is to use ; (sequential composition) and parentheses to combine expressions:

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = 
        { Name = ((if name.StartsWith("A") then failwith "Haiz"); name) } 
like image 176
pad Avatar answered Oct 28 '22 04:10

pad