gpt4 book ai didi

f# - 如何执行模块做 block ?

转载 作者:行者123 更新时间:2023-12-04 20:04:19 25 4
gpt4 key购买 nike

我需要在我想通过利用 do block 来完成的模块中进行一些设置。奇怪的是,我的 do block 似乎从未被击中。

更奇怪的是,如果我将模块代码加载到 fsi 中,它确实会被命中。这是我的例子:

Main.fs

[<EntryPoint>]
let main args =
printfn "%b" TestNamespace.M.x
0

TestModule.fs

namespace TestNamespace

module M =
do
printfn "In do"
failwith "Error" // this is line 6

let x = true

当我运行编译后的可执行文件时,我得到了

>test.exe
true

为什么没有抛出异常?如果我自己在 FSI 中运行模块,我会得到

In do
System.Exception: Error
at <StartupCode$FSI_0006>.$FSI_0006.main@() in C:\Projects\Personal2\Playground\fsscripts\fsscripts\TestModule.fs:line 6
Stopped due to error

所以它得到了异常(exception)。

我在反编译中看到 do 初始化器被滚动到一个单独的类中

namespace \u003CStartupCode\u0024fsscripts\u003E
{
internal static class \u0024Library1
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
internal static int init\u0040;

static \u0024Library1()
{
ExtraTopLevelOperators.PrintFormatLine<Unit>((PrintfFormat<Unit, TextWriter, Unit, Unit>) new PrintfFormat<Unit, TextWriter, Unit, Unit, Unit>("In do"));
Operators.FailWith<Unit>("Error");
bool x = M.x;
}
}
}

VS实际的模块代码:

namespace TestNamespace
{
[CompilationMapping(SourceConstructFlags.Module)]
public static class M
{
public static bool x
{
[DebuggerNonUserCode] get
{
return true;
}
}
}
}

那么我如何确保 do block 真正被执行?

--

编辑,鉴于上面的示例算作一个简单的常量表达式,因此不会产生可观察的初始化,为什么以下也不起作用?

[<EntryPoint>]
let main args =
printfn "%d" (TestNamespace.M.x id 1)
0
namespace TestNamespace

module M =
do
printfn "In do"
failwith "Error"

let x f a = f a

这样打印出1没问题。


编辑,在重新阅读 Tomas 的评论后,因为函数被认为是常量表达式。

最佳答案

有关问题的详细解释,请参阅 this previous SO question 的答案.重要的一点是:

the static initializer for the file is executed on first access of a value that has observable initialization

现在,“可观察初始化”是一个有点棘手的想法,但简单的常量初始化肯定没有可观察初始化 - 这就是不执行 do block 的原因。您可以诱使编译器认为存在一些命令性操作,例如通过添加 do ():

module M = 
do
printfn "In do"
failwith "Error" // this is line 6

let x = (do ()); true

关于f# - 如何执行模块做 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18619093/

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