返回中等复杂F#类型签名的困难
我定义了F#树和堆栈类型,堆栈上有一个pop成员。我无法在pop结果上获得正确的类型签名。以下是我尝试使用pop之前的代码:返回中等复杂F#类型签名的困难,f#,F#,我定义了F#树和堆栈类型,堆栈上有一个pop成员。我无法在pop结果上获得正确的类型签名。以下是我尝试使用pop之前的代码: type Tree<'a> = | Tree of 'a * 'a Tree * Tree<'a> | Node of 'a | None type 'a Stack = | EmptyStack | Stack of 'a * 'a Stack member x.pop = function
type Tree<'a> =
| Tree of 'a * 'a Tree * Tree<'a>
| Node of 'a
| None
type 'a Stack =
| EmptyStack
| Stack of 'a * 'a Stack
member x.pop = function
| EmptyStack -> failwith "Empty stack"
| Stack(hd, tl) -> (hd:'a), (tl:Stack<_>)
let myTree = Tree("A", Tree("B", Node("D"), None), Tree("C", Tree("E", None, Node("G")), Tree("F", Node("H"), Node("J"))))
let myStack = Stack((myTree, 1), Stack.EmptyStack)
抛出:
stdin(22,24):错误FS0001:此表达式应具有类型
('a*'b)*'c
但这里有一种类型
(树*int)堆栈->(树*int)*(树*int)堆栈
//let(tree:tree,level:int),z:Stack=myStack.pop
let(tree:tree,level:int),z:Stack,level:int),z=myStack.pop
//let(tree:tree,level:int),z:Stack=myStack.pop
上述未注释的尝试引发:
stdin(16,46):错误FS0001:此表达式应具有类型
(Tree问题在于,
pop
这里有一个实例方法使用一个参数(由于函数
),但您希望它是一个实例方法使用零参数(即单位),如
[编辑]
但实际上,由于Stack
在这里是不可变的,因此将pop
作为实例成员实现是没有意义的,因为它实际上更像peek。因此,您可能希望将其作为配套模块中的一个函数实现(或/或作为Stack
的静态成员实现,以与其他.NET语言兼容):
问题是,
pop
这里是一个实例方法,它只接受一个参数(由于函数
),但您希望它是一个实例方法,它接受零个参数(即单位),如
[编辑]
但实际上,由于Stack
在这里是不可变的,因此将pop
作为实例成员实现是没有意义的,因为它实际上更像peek。因此,您可能希望将其作为配套模块中的一个函数实现(或/或作为Stack
的静态成员实现,以与其他.NET语言兼容):
let (tree, level), z = myStack.pop
//let (tree:Tree<_>, level:int), z:Stack<Tree<_>*int> = myStack.pop
let (tree:Tree<_>, level:int), z:Stack<'a> = myStack.pop
//let (tree:Tree<'a>, level:int), _ = myStack.pop
//let (tree:Tree<string>, level:int), z:Stack<Tree<string>*int> = myStack.pop
type 'a Stack =
| EmptyStack
| Stack of 'a * 'a Stack
member x.pop() =
match x with
| EmptyStack -> failwith "Empty stack"
| Stack(hd, tl) -> (hd:'a), (tl:Stack<_>)
let (tree,level), z = myStack.pop()
type 'a Stack = \\'
| EmptyStack
| Stack of 'a * 'a Stack
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Stack =
let pop = function
| EmptyStack -> failwith "Empty stack"
| Stack(hd, tl) -> (hd:'a), (tl:Stack<_>)
let (tree, level), z = Stack.pop myStack