我创建了一个不可变的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):错误 FS0030:
值限制。值“test”已被推断为具有泛型类型
val 测试:队列
要么将“test”定义为一个简单的数据术语,要么将其设为具有显式函数的函数
参数,或者,如果您不希望它是通用的,请添加类型注释。
基本上,我想要在Set
模块允许我编写:
> let test = Set.empty;;
val test : Set<'a>
我该如何修改我的Queue
类允许用户创建空队列?
您需要使用 GeneralizedValueAttribute,如下所示:
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>
您可以在中阅读更多相关信息语言规范 http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec2.aspx.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)