gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:05:36 42 4
gpt4 key购买 nike

我创建了一个不可变的 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/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com