如何修改我的Queue类以允许用户在F#中创建未指定类型的空队列? [英] How should I modify my Queue class to allow users to create empty queues of unspecified type in F#?

查看:89
本文介绍了如何修改我的Queue类以允许用户在F#中创建未指定类型的空队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在F#中创建了一个不可变的队列,如下所示:

I have created an immutable Queue in F# as follows:

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 ,但是我得到一个有价值的限制例外:

I want to create an instance of an empty Queue, however I get a value-restriction exception:

> let test = Queue.empty;;

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




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

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 模块中看到,它允许我写:

Basically, I want the same kind of functionality seen in the Set module which allows me to write:

> let test = Set.empty;;

val test : Set<'a>

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

How can I modify my Queue class to allow users to create empty queues?

推荐答案

您需要使用GeneralizableValueAttribute,一个:

You need to use GeneralizableValueAttribute, a 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>

您可以在语言规格

这篇关于如何修改我的Queue类以允许用户在F#中创建未指定类型的空队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆