Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Types 将运算符的使用限制为单个类_Types_F#_Operators - Fatal编程技术网

Types 将运算符的使用限制为单个类

Types 将运算符的使用限制为单个类,types,f#,operators,Types,F#,Operators,Q:在F#中,是否绝对有必要在类型声明本身中声明类型的运算符? 为了对某些类型实施一些额外的安全性,我想定义一个类型,但只允许从特定类对该类型进行操作。我有以下代码: /// Tracks identity of an Event type EventID = EventID of int let defaultEventID = EventID 0 /// Singleton to generate IDs for Events type EventIDManager private ()

Q:在F#中,是否绝对有必要在类型声明本身中声明类型的运算符?

为了对某些类型实施一些额外的安全性,我想定义一个类型,但只允许从特定类对该类型进行操作。我有以下代码:

/// Tracks identity of an Event
type EventID = EventID of int

let defaultEventID = EventID 0

/// Singleton to generate IDs for Events
type EventIDManager private () =    
    let mutable currentID = defaultEventID
    static let instance = EventIDManager()
    static member Instance = instance

    /// Operator definition in question
    static member inline private (+.) (EventID(a), EventID(b)) = EventID(a + b)

    /// Simply increments IDs for now
    member private __.advanceID () =
        currentID <- currentID +. (EventID 1) /// Compiler warning here

    member this.generateID () =
        let cur = currentID
        this.advanceID ()
        ///return ID
        cur

    member __.getCurrentID () = currentID
即使我以以下方式实现添加,我仍然会收到相同的警告:

static member inline private (+.) (e1:EventID) (e2:EventID) =
    match e1, e2 with EventID a, EventID b -> EventID(a + b)
如果将运算符声明移动到类型定义,问题就会消失,但我很好奇是否可以将运算符定义保留在
EventIDManager
类中。这可能吗?

F#中的静态成员通常需要将类名放在前面才能看到它。我要做的是(特别是因为您只需要一个私有操作符),将其作为let绑定编写。因此,最重要的是你的所有成员

let (+.) (EventID a) (EventID b) = EventID(a + b)

您应该能够从EventIDManager类而不是其他任何地方使用它。

编译器抱怨
内联
标记,但除此之外,只要它在其他成员函数之前声明,它就可以工作。它看起来像是
inline
它必须是实际模块内部的
private
。。。
let (+.) (EventID a) (EventID b) = EventID(a + b)