我应该如何修改我的Queue类以允许用户在F#中创建未指定类型的空队列?

Jul*_*iet 6 f# data-structures

Queue在F#中创建了一个不可变的如下:

type Queue<'a>(f : 'a list, r : 'a list) =    
    let check = function
        | [], r -> Queue(List.rev r, [])
        | f, r -> Queue(f, r)

    member this.hd =
        match f with
        | [] -> failwith "empty"
        | hd :: tl -> hd

    member this.tl =
        match f, r with
        | [], _ -> failwith "empty"
        | hd::f, r -> check(f, r)

    member this.add(x) = check(f, x::r)

    static member empty : Queue<'a> = Queue([], [])
Run Code Online (Sandbox Code Playgroud)

我想创建一个空的实例Queue,但是我得到一个值限制异常:

> let test = Queue.empty;;

  let test = Queue.empty;;
  ----^^^^
Run Code Online (Sandbox Code Playgroud)

C:\ Documents and Settings\juliet\Local Settings\Temp\stdin(5,5):错误FS0030:值限制.值'test'被推断为具有泛型类型val测试:Queue <'_ a>将'test'定义为一个简单的数据项,使其成为具有显式参数的函数,或者,如果您不打算将其作为通用参数,添加类型注释.

基本上,我想要在Set模块中看到的相同类型的功能允许我写:

> let test = Set.empty;;

val test : Set<'a>
Run Code Online (Sandbox Code Playgroud)

如何修改我的Queue类以允许用户创建空队列?

Bri*_*ian 6

你需要使用GeneralizableValueAttribute,la:

type Queue<'a>(f : 'a list, r : 'a list) =  // '
    let check = function
        | [], r -> Queue(List.rev r, [])
        | f, r -> Queue(f, r)

    member this.hd =
        match f with
        | [] -> failwith "empty"
        | hd :: tl -> hd

    member this.tl =
        match f, r with
        | [], _ -> failwith "empty"
        | hd::f, r -> check(f, r)

    member this.add(x) = check(f, x::r)
module Queue =    
    [<GeneralizableValue>]
    let empty<'T> : Queue<'T> = Queue<'T>([], []) // '

let test = Queue.empty
let x = test.add(1)       // x is Queue<int>
let y = test.add("two")   // y is Queue<string>
Run Code Online (Sandbox Code Playgroud)

您可以在语言规范中阅读更多相关内容.