Good question is why do you need this constructor?

By on 5/29/2009 12:15 AM ()

You must have a constructor for struct, or am I wrong(see error below)?
Initially I used a record for Rect, but had to convert it to a struct so that arrays of them are more space efficient. Would be happy to be able to do this:

[<Struct>]
type MyClass() =
let mutable x = 0;;

let mc = new MyClass (x=4);;
---------------------------------------------------------------------
> [<Struct>]
type MyClass() =
let mutable x = 0
member this.X with get() = x
and set(n) = x <- n
;;

type MyClass() =
-------^^^^^^^

stdin(33,8): error FS0081: Implicit object constructors for structs must take at least one argument

By on 5/29/2009 1:26 AM ()

You must have a constructor for struct, or am I wrong(see error below)?

The diagnostic here is misleading. Structs cannot use the implicit constructor syntax and 'let's, they must use explicit constructor syntax and 'val's, see also [link:msdn.microsoft.com] . But there's no reason you need to define any constructor at all (you can have just the autogenerated default constructor be the only one):

1
2
3
4
5
6
7
8
9
 

[<Struct>]

type MyStruct =
    val mutable x : int

let mc = new MyStruct(x=4) // calls MyStruct() and then does .x <- 4
By on 5/29/2009 7:09 AM ()

Default constructor for structs is always autogenerated.

By on 5/29/2009 6:10 AM ()

Thanks. I understand the better way to instantiate this struct would be by just setting the properties and not having the constructor at all.

By on 5/29/2009 1:06 AM ()

The same thing is true with a class if the class has a default constructor. In both cases the call becomes ambiguous. Note that F# also allows you to 'assign properties' in a constructor call, a la

1
2
3
4
5
6
7
8
9
10
 

type MyClass() =
    let mutable x = 0
    member this.X with get() = x
                  and set(n) = x <- n

let mc = new MyClass(X=4)                  

and so in this case that 'property assignment' shorthand is an ambiguous conflict with the 'named parameter' shorthand.

By on 5/28/2009 11:52 PM ()

"In both cases the call becomes ambiguous. Note that F# also allows you to 'assign properties' in a constructor call"

Using named argument here should not be ambiguous since x_tl field is immutable, is not it?

By on 5/29/2009 2:10 PM ()

"In both cases the call becomes ambiguous. Note that F# also allows you to 'assign properties' in a constructor call"

Using named argument here should not be ambiguous since x_tl field is immutable, is not it?

You're right. I'll file a low-priority bug (I don't know if we'll fix, since there are ample workarounds).

By on 5/29/2009 2:28 PM ()

You can always work around named arguments :-)

By on 5/29/2009 2:58 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper