功能包装问题:X <|乐趣()->一个

发布于 2024-12-03 02:32:49 字数 410 浏览 1 评论 0 原文

所以我只是想问为什么这有效:

let internal X th =
    foo()
    th()
    bar()

let Start() = 
    X <| fun () -> ( foo(); bar(); etc... )

这不起作用:

let internal XD A =
    let X th =
        foo()
        th()
        bar()
    (X <| fun () -> A)

let Start() = 
    XD ( foo(); bar(); etc... )

它对我来说看起来是一样的,但第一个变体作为包装器工作,我完全不明白第二个变体是如何工作的。

So I just wanted to ask why this works :

let internal X th =
    foo()
    th()
    bar()

let Start() = 
    X <| fun () -> ( foo(); bar(); etc... )

And this doesn't work :

let internal XD A =
    let X th =
        foo()
        th()
        bar()
    (X <| fun () -> A)

let Start() = 
    XD ( foo(); bar(); etc... )

it's looking like the same for me but first variant works as wrapper and I completely can't understand how second variant works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

韶华倾负 2024-12-10 02:32:49

我认为令人困惑的是,在您的第二个版本中,变量 A 只是一个 unit。 F# 编译器根据以下事实推断这一点:您从用作 th 的函数返回 A,并且 th 的类型为 unit ->单位。这意味着在单步执行 XD 之前,会在 Start 中调用 foo

然而,很难说出您期望的结果是什么。您是否想将 foo 作为函数传递给 XD,而不是立即调用它?如果是,那么您需要:

let internal XD A =
    let X th =
        foo()
        th()
        bar()
    (X <| fun () -> A()) // Change: Call A with unit argument: 'A ()'

XD foo // Change: Pass a function instead of calling it

I suppose that the confusing thing is that in your second version, the variable A is just a unit. The F# compiler infers this from the fact that you return A from a function that's used as th and the type of th is unit -> unit. This means that foo is called in Start before stepping in XD.

However, it is a bit difficult to tell what results were you expecting. Did you want to pass foo to XD as a function, instead of calling it immediately? If yes, then you'd need:

let internal XD A =
    let X th =
        foo()
        th()
        bar()
    (X <| fun () -> A()) // Change: Call A with unit argument: 'A ()'

XD foo // Change: Pass a function instead of calling it
听闻余生 2024-12-10 02:32:49

以下是您想要实现的第二个版本的正确代码(不使用惰性值的 lambda)。

let internal XD (A:Lazy<unit>) =
    let X th =
        foo()
        th()
        bar()
    X <| (fun () -> A.Force())

let Start() = 
    XD ( lazy(foo(); bar();) )

The below is the correct code for 2nd version for what you want to achieve (without lambda using lazy values).

let internal XD (A:Lazy<unit>) =
    let X th =
        foo()
        th()
        bar()
    X <| (fun () -> A.Force())

let Start() = 
    XD ( lazy(foo(); bar();) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文