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

标签 data-structures f#

我创建了一个不可变的 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([], [])

我想创建一个空 Queue 的实例,但是我得到一个值限制异常:
> let test = Queue.empty;;

  let test = Queue.empty;;
  ----^^^^

C:\Documents and Settings\juliet\Local Settings\Temp\stdin(5,5): error FS0030: Value restriction. The value 'test' has been inferred to have generic type val test : Queue<'_a> Either define 'test' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.



基本上,我想要 Set 中看到的相同类型的功能。允许我编写的模块:
> let test = Set.empty;;

val test : Set<'a>

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

最佳答案

您需要使用 GeneralizableValueAttribute,例如:

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>

您可以在 language spec 中了解更多信息。 .

关于data-structures - 我应该如何修改我的 Queue 类以允许用户在 F# 中创建未指定类型的空队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/927400/

相关文章:

f# - 尝试在 f# 中验证 CSV 数据

python - 在 pdist 压缩距离矩阵中找到最小值的索引

python - python 列表的子集

f# - 是否可以要求静态解析的类型参数是泛型类型?

wcf - 在 F# Web 服务中传递对象与记录

f# - F# 中的 AutoOpen 属性

c# - 我可以在 MethodInfo 对象上找到应用的泛型参数的位置吗?

java - java中具有不同数据类型的队列

c++ - 在链表中查找节点的算法

c - 返回一个列表作为数据结构契约