为什么F#Interactive在不变值定义方面的行为与编译器不同? [英] Why does F# Interactive behave differently than compiler with regards to immutable value definition?

查看:105
本文介绍了为什么F#Interactive在不变值定义方面的行为与编译器不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 John Palmer的

这种重新定义仅在fsi中有效.

This sort of redefinition will only work in fsi.

在使用F#Interactive(fsi)时,我想我下意识地知道它,但从未关注它.

In working with F# Interactive (fsi) I guess I subconsciously knew it, but never paid attention to it.

现在很明显,为什么会有区别呢?

Now that it is apparent, why the difference?

更具体地说,请解释fsi和编译器之间的内部差异如何,从而这是由设计或差异导致的?

More specifically please explain how the internals are different between fsi and the compiler such that this occurs by design or result of differences?

如果答案能详细说明保持绑定的内部结构,那么

If the answer can elaborate on the internal structures that hold the bindings that would be appreciated.

推荐答案

语义与FSI将交互式提交编译到FSI会话的方式是一致的:每个交互式提交都被编译为module,以供随后的交互式提交使用.

The semantics are consistent with the way FSI compiles interactive submissions to an FSI session: each interactive submission is compiled as module which is open to subsequent interactive submissions.

以下内容与FSI的实际操作非常接近,并说明了let绑定阴影如何在交互式提交中起作用:

The following is close to what FSI actual does and illustrates how let binding shadowing works across interactive submissions:

FSI提交#1:let x = 1;;

module FSI_1 = 
    let x = 1

open FSI_1 //FSI_1.x is now bound to 1 and available at the top level

FSI提交#2:let x = 2;;

module FSI_2 = 
    let x = 2

open FSI_2 //FSI_1.x is now shadowed by FSI_2.x which is bound to 2 and available at the top level

您可以在FSI应用程序域中的FSI_ASSEMBLY程序集上使用反射来查看如何编译动态FSI程序集的实际详细信息.每个交互式提交实际上都是使用命名模式FSI_####作为模块(.NET类)发出的. FsEye使用以下事实来发现FSI顶级绑定的状态:

You can see the actual details how how the dynamic FSI assembly is compiled by using reflection on the FSI_ASSEMBLY assembly within the FSI app domain. Each interactive submission is literally emitted as a module (.NET class) with the naming pattern FSI_####. FsEye uses these facts to discover the state of FSI top-level bindings: https://code.google.com/p/fseye/source/browse/tags/2.0.1/FsEye/Fsi/SessionQueries.fs#24

关于@JohnPalmer答案的关键要点是顶级FSI定义 不能被突变,当重新定义"它们时,它们只是被遮盖了.我们可以显示如下:

The key takeaway in regard to @JohnPalmer's answer is that top-level FSI definitions cannot be mutated, when they are "redefined" they are merely being shadowed. We can show this as follows:

> let x = 1;; //our original definition of x
val x : int = 1

> let f () = x;; //capture x
val f : unit -> int

> let x = 2;; //shadow our original definition of x
val x : int = 2

> f();; //returns the original x value, which is still 1 rather than 2
val it : int = 1

这篇关于为什么F#Interactive在不变值定义方面的行为与编译器不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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