F#记录:具有相同名称的字段 [英] F# Records: Fields With Identical Names

查看:76
本文介绍了F#记录:具有相同名称的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下记录定义:

type A = { F1 : int; F2 : int }
type B = { F1 : int; F3 : int } 

// error FS0656: This record contains fields from inconsistent types   
let a1 = { F1 = 1; F2 = 2 } 

// this works
let a2 = { A.F1 = 1; F2 = 2 }

我不明白,为什么a1会导致错误.

I don't understand, why a1 results in an error.

我能找到所有为什么必须使用a2方式的示例都假设A和B中的所有字段名称都具有相同的名称-这当然是模棱两可的,但A和B不应至少有一个不同的字段时可以区分?

All the examples I could find of why you have to do it the a2-way assume that all the field-names in A and B have the same name - which is of course ambiguous, but shouldn't A and B be distinguishable when having at least one distinct field?

也许这只是F#评估的方式,并且将类型名称添加到第一个字段当然没什么大不了的,但是我很好奇.

Maybe this ist just the way F# evaluates this and adding the type name to the first field is of course no big deal, but I'm just curious.

感谢您提供的答案,这些答案使我注意到了一个很奇怪的问题:第一次评估时,整个代码段都起作用(VS 2010中的ALT + Enter).

Thanks for the answers which helped me notice something rather strange: The whole snippet works, when I evaluate it the first time (ALT+Enter in VS 2010).

当我尝试第二次评估时,出现错误.

When I try to evaluate a second time, I get the error.

如果没有人能重现这一点,我的VS安装可能会令人沮丧...

If nobody can reproduce this my installation of VS is probably borked...

EDIT2(好的,是时候在这里创建帐户了,抱歉!) 感谢wmeyer(和其他所有人)花时间研究问题并使我意识到我对FSI的误解.全部清除了!

EDIT2 (alright, time to create an account here, sorry for the edits) Thanks wmeyer (and everyone else) for taking the time to look at the problem and making me aware of my misunderstanding how FSI works. All cleared up now!

推荐答案

我认为您的安装不成功.

I don't think your installation is borked.

在第二次求值时该代码不起作用是有道理的.旧的类型AB仍然存在,它们只是A和新的A.

It makes sense that the code does not work when evaluated the second time. The old types A and B still exist, they are just shadowed.
Field names, on the other hand, are never shadowed. (Otherwise you could never have the same field name in two different records.)
The "union of all possible records" (see Massif's answer) has more than one element now: the old (shadowed) A and the new A.

要解决此问题,您可以在两次运行之间使用F#Interactive上下文菜单中的重置会话".或将您的代码包装在模块中(这样旧的记录类型将既不可访问,也不会在范围内).

To solve this problem, you could use "Reset session" from the F# Interactive context menu in between runs. Or wrap your code in a module (then the old record types will be neither accessible nor in scope).

这篇关于F#记录:具有相同名称的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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