我是F#的新手,所以请怜悯。试图在F#中模拟租车业务。我的类型是:
客户
司机
车
VehicleType
RentalAgreement 未实现
我的具体问题是,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
答案 0 :(得分:3)
是的,一个有区别的联合就像任何其他类型一样,可以用作任何字段,属性,构造函数参数等的类型。
只需将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
。
答案 1 :(得分:0)
是的,只需将该成员添加到该类中,并将其包含在具有所需值的构造函数中。
// 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