F# 中的 AutoOpen 属性 [英] AutoOpen attribute in F#

查看:23
本文介绍了F# 中的 AutoOpen 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 AutoOpen 属性的推荐原则是什么?

What is the recommended doctrine for using the AutoOpen attribute ?

(这个问题可能是继续何时使用模块函数VS静态函数类似命名类型 )

(This question is probably is in continuation to when to use module function VS static function on similarly named type )

Expert F# 指出这在您定义临时顶级运算符时很有用和功能:"

Expert F# states that "This can be useful when you’re defining ad hoc top-level operators and functions:"

所以这似乎是为了减少代码组织中模块的作用,当您在技术上需要一个人来编写代码但您从客户端的角度删除它的存在时.

So this seems to be here to kind of diminish the module role in the code organization, when you technically need one to write the code but you remove its existence from a client perspective.

还有别的吗?什么时候用?

Is there something else ? When do you use it ?

推荐答案

我认为 AutoOpen 属性的主要用途是当你想让一些 let-bound 值在你的用户库打开一个命名空间.这就是属性非常有用的地方,因为我认为库通常应该导出 namespaces 中的所有定义,但是出于某些目的,您需要导出 values 并且值不能在其中定义一个命名空间.

I think the main use for the AutoOpen attribute is when you want to make some let-bound values available when the user of your library opens a namespace. This is where the attribute is very useful, because I think libraries should generally export all definitions in namespaces, but for some purposes you need to export values and values cannot be defined inside a namespace.

这是一个来自 F# 异步扩展 的示例,它定义了一个计算构建器,因此它需要导出 asyncSeq 值(但同时,所有功能都包含在命名空间中):

Here is an example from F# async extensions which defines a computation builder and thus it needs to export asyncSeq value (but at the same time, all functionality is wrapped in a namespace):

namespace FSharp.Async

type AsyncSeq<'T> = (* ... *)
type AsyncSeqBuilder() = (* ... *)

[<AutoOpen>]
module GlobalValues = 
  let asyncSeq = AsyncSeqBuilder()

库的用户只需编写打开FSharp.Async,他们就会看到asyncSeq.我认为相同的模式用于各种数学库(您还想导出简单命名的函数.)

The user of the library can just write open FSharp.Async and they will see asyncSeq. I think the same pattern is used with various math libraries (where you also want to export simple-named functions.)

对于模块(例如ListSeq),我想大多数人不使用open 并通过模块访问功能名称(例如 List.map),因此尽管您可以将其用于嵌套模块,但我并没有经常看到这种情况.

For modules (e.g. List and Seq), I think most of the people do not use open and access the functions via a module name (such as List.map), so although you can use this for nested modules, I have not seen that as frequently.

这篇关于F# 中的 AutoOpen 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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