递归地填充字典?
我正在测试以下代码以递归地填充字典。然而,类型推断似乎无法识别字典类型。我尝试过使用类型注释,但这似乎没有帮助。
在递归例程中使用字典是否有一些限制?我是否需要使字典可变,因为我希望在迭代期间更改它。
open System
open System.Collections.Generic
////dictionary recursion test
let pop_dict tlist =
// let rec inner tlist acc ddict:Dictionary<string,int> =
let rec inner tlist acc ddict =
match tlist with
| [] -> ddict.Add ("dummykey", acc)
| x::xs -> inner xs (x::acc) ddict
let ddict = Dictionary<string,int>()
inner tlist [] ddict
// Main Entry Point
let main() =
let tlist = [1;2;3;4]
let d = pop_dict tlist
main()
I'm testing the following code to populate a dictionary recursively. However the type inference does not seem to recognize the dictionary type. I've tried using a type annotation but that did not seem to help.
Are there some restrictions on the use of dictionaries in a recursive routine. Do I need to make the dictionary mutable since I expect to change it during iterations.
open System
open System.Collections.Generic
////dictionary recursion test
let pop_dict tlist =
// let rec inner tlist acc ddict:Dictionary<string,int> =
let rec inner tlist acc ddict =
match tlist with
| [] -> ddict.Add ("dummykey", acc)
| x::xs -> inner xs (x::acc) ddict
let ddict = Dictionary<string,int>()
inner tlist [] ddict
// Main Entry Point
let main() =
let tlist = [1;2;3;4]
let d = pop_dict tlist
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,你们的类型不匹配。
您正在尝试将
int 列表
(这就是acc
的含义)添加到应该包含int
的字典中。然而除此之外,编译器无法推断 ddict 类型的原因是。请记住,当类型检查器确定函数的类型时,它不会查看稍后调用的内容。它仅具有以下可用信息:
这意味着,它在编译函数时了解的关于 ddict 的唯一信息是它有一个名为
Add
的方法,该方法<代码>字符串*'一个列表-> ?。要修复此问题,请更改
为
您仍然遇到字典上不匹配类型的问题,因此,如果您打算存储
,您可能希望它是
其中。Dictionary
>int listFirst of all, your types don't match up.
You're trying to add an
int list
(which is whatacc
is) to a dictionary that is supposed to containint
s.Apart from that, however, the reason that the compiler cannot infer the type of
ddict
is. Remember, when the type checker determines types for the function, it doesn't look at what it gets called with later. It only has the following information available:That means, that the only information it knows about
ddict
when it compiles the function, is that it has a method namedAdd
, whichstring * 'a list -> ?
.To fix it, change
to
You still have the trouble with the mismatching types on the dictionary, however, so you probably want it to be
Dictionary<string, int list>
, if you plan on storingint list
s in it.这就是你想要的吗?
is that what you wanted?