我是 F# 新手,所以请怜悯。尝试使用 F# 为汽车租赁业务建模。我的类型是:
我的具体问题是 F# 类可以有受歧视联盟的成员吗?汽车应该有一个属性来反映它是什么类型的车辆...紧凑型、轿车、卡车等...下面是我到目前为止的代码...
namespace DSL2
// a DU
type vehicleType = Truck | Compact | Econ | Sedan
// a record
type Customer = {firstName: string; lastName: string; gender: string}
//a class implicit ctor'tion
type Car(numdoors:int , make: string , year:int) = class
member this.NumDoors = numdoors
member this.Make = make
member this.Year = year
end
//a class explicit ctor'tion
type Car2 = class
val NumDoors: int
val Make: string
val Year: int
(*first ctor*)
new (numDoors, make, year) =
{NumDoors = numDoors; Make = make; Year = year}
end
是的,可区分联合就像任何其他类型一样,可以用作任何字段、属性、构造函数参数等的类型。
只需将
vehicleType
类型的参数添加到 Car
构造函数即可:
type Car(numdoors:int, make: string, year:int, vehicleType : vehicleType) = class
member this.NumDoors = numdoors
member this.Make = make
member this.Year = year
member this.VehicleType = vehicleType
end
请注意,使用首字母小写字母命名类型是不好的 F# 风格,因此我建议将其重命名为
VehicleType
。
是的,只需将成员添加到类中并将其包含在具有所需值的构造函数中即可。
// a DU
type vehicleType = Truck | Compact | Econ | Sedan
// a record
type Customer = {firstName: string; lastName: string; gender: string}
//a class implicit ctor'tion
type Car(numdoors:int , make: string , year:int) = class
member this.NumDoors = numdoors
member this.Make = make
member this.Year = year
end
//a class explicit ctor'tion
type Car2 = class
val NumDoors: int
val Make: string
val Year: int
val DU: vehicleType
(*first ctor*)
new (numDoors, make, year, cust) =
{NumDoors = numDoors; Make = make; Year = year; DU = Truck }
end