如何在 F# 上制作无参数的功能包装器?
这是我的代码:
let go thriller =
work.ListPos.Clear()
thriller
work.Thread.Start()
member X.Start() =
work.ListPos.Add <| new Packet( connector.Authorize("admin","1") ) |> go
所以它不起作用。我使用带有参数的包装器,如下所示:
let inconnection thriller =
using <| new SqlConnection(insql) <| fun X -> X.Open(); thriller X;
inconnection <| fun X ->
我不能在没有参数的情况下以这种方式使用它,因为我没有 X (参数),但是如何创建没有参数的 lambda ?
谢谢。
here is my code :
let go thriller =
work.ListPos.Clear()
thriller
work.Thread.Start()
member X.Start() =
work.ListPos.Add <| new Packet( connector.Authorize("admin","1") ) |> go
So it doesn't work. I used wrapper with parameter like this :
let inconnection thriller =
using <| new SqlConnection(insql) <| fun X -> X.Open(); thriller X;
inconnection <| fun X ->
I can't use it this way without parameters because I got no X (parameter) but how to create lambda without parameters ?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
()
用于空 lambda 参数列表或空主体:Use
()
for an empty lambda parameter list or for an empty body:据我所知,您正在尝试实现“中间的洞”模式 - 即运行一些初始化,然后运行用户指定的函数,然后运行一些清理。
正如 dahlbyk 已经指出的那样,您需要将
go
操作传递给unit -> 类型的 function 。单位。可以这样写:
旁白。您的另一个示例并不是真正惯用的 F# 代码。
using
函数可以替换为use
关键字,这明显更容易使用:更棘手的选项。
或者,您还可以将
use
关键字用于处理 SQL 连接等资源之外的其他用途。这可以使您的 go 函数变得更好(但这取决于您的具体情况)。这个想法是,您将能够编写:为此,您需要将
go
定义为返回执行清理的IDisposable
的函数:As far as I can see, you're trying to implement the "hole in the middle" pattern - that is, run some initialization, then run a function specified by the user and then run some cleanup.
As dahlbyk already pointed out, you need to pass your
go
operation a function of typeunit -> unit
. This can be written like this:Aside. Your other example isn't really idiomatic F# code. The
using
function can be replaced with ause
keyword, which is significantly easier to use:More tricky option.
Alternatively, you can also use the
use
keyword for other things than disposing of resources like SQL connections. This could make yourgo
function even nicer (but it depends on your particular case). The idea is that you'll be able to write:To do this, you need to define
go
as a function that returnsIDisposable
that performs the cleanup: