我在 F# 文件中有以下代码:
module ORDERS
type OrderId = // TypeName
| OrderId of string // LabelName: same as TypeName!
with
static member getValue (OrderId orderId) =
orderId
在另一个文件中,我可以使用这样的功能:
// This code works.
module Application
open ORDERS
let x = OrderId "1111"
let extractedValue =
x
|> OrderId.getValue
但是,如果我尝试删除"打开的订单"并将代码替换为它们的完整路径,则会出现错误:
// This code fails.
module Application
// This is OK
let x2 = ORDERS.OrderId "11111"
// This has error!
let extractValue2 =
x2
|> ORDERS.OrderId.getValue
我相信原因是在第二个代码中,F# 无法区分类型名称"OrderId"和标签名称"OrderId">
问题:
- 为什么删除"未结订单",但指定完整路径会导致代码失败?这两个代码(带有"open ORDERS";没有"open ORDERS",但指定函数的全名(不是等价的吗?
附加问题:
以不同的方式重命名TypeName和LabelName是否更好,这样它们就不会相互冲突?例如
module ORDERS type OrderIdType = // TypeName | OrderIdLabel of string // LabelName: different from TypeName! with static member getValue (OrderIdLabel orderId) = orderId
谢谢。
您可以通过将
静态方法替换为模块级 getOrderIdValue 函数来实现如下所示:
module ORDERS =
type OrderId = // TypeName
| OrderId of string // LabelName: same as TypeName!
with
static member getValue (OrderId orderId) =
orderId
let getOrderIdValue (OrderId orderId) =
orderId
module Application =
open ORDERS
let x = OrderId "1111"
let extractedValue =
x
|> OrderId.getValue
module ApplicationWithoutOpenOrders =
// This is OK
let x2 = ORDERS.OrderId "11111"
// This has error!
let extractValue2 =
x2
|> ORDERS.getOrderIdValue