在Elm中,“exposing(..)”是什么意思?

17
我在尝试理解Elm的第一个范例,它有这样一段代码:

import Graphics.Element exposing (..)

请问exposing (..)是什么意思?
3个回答

19

exposing (..) 允许你直接调用包中所有的函数。

例如,如果SamplePackage有函数x和y,import SamplePackage 将允许你调用 SamplePackage.xSamplePackage.y,而 import SamplePackage exposing (..) 则允许你直接调用 xy,无需指定它们所在的包。

请注意,import SamplePackage exposing (x) 允许你直接调用 x,但你仍然需要使用 SamplePackage.y 调用 y。同样地,import SamplePackage exposing (x, y) 将允许你调用 xy,但不允许你调用包中的其他函数。


4
如果您使用此语法导入了两个具有相同名称方法“X”的包,会发生什么? - Jānis

8
这意味着您可以直接在Graphics.Element模块中访问所有内容,无需先指定软件包。由于此示例仅使用“show”和“Element”,因此您可以将导入行更改为:
import Graphics.Element exposing (Element, show)

对于这个例子,它仍然可以正常工作。


我认为你的回答比被采纳的更好,因为你指出了 exposing (..)exposing (Element, show) 之间的区别。 - wiser
1
我建议还要补充说明,如果只使用了 import Graphics.Elements,你仍然可以通过以下方式访问 Graphics.Element 模块中的所有公共内容:Graphics.Element.ElementGraphics.Element.show - wiser

5

这是一个旧问题,但我仍然会通过另一种思路来解释exposing (..),并解释一下为什么通常不是一个好主意。如果你有Python编程背景,那么你可以将其视为Python中的from module import *。这是Elm代码:

import Graphics.Element exposing (Element, show)

在Python中,它看起来会像这样:

from Graphics.Element import Element, show

而这段 Elm 代码:

import Graphics.Element exposing (..)

在Python中,它会像这样:

from Graphics.Element import *

前两个将仅向您当前模块的命名空间添加名称Element和show;后面两个示例将添加Graphics.Element中的所有名称到您的命名空间。当您第一次编写模块时,这很方便,因为您可能还不知道您将需要从Graphics.Element中使用哪些名称。但是,一旦您完成了模块的编写,最好回过头来将exposing (..)更改为exposing (just, the, names, you, need)。这样,您可以确保以后不会发生任何名称冲突。
例如,如果您编写了一个名为myGraphics的模块,在其中创建了一个名为rotatedImage的函数,因为它目前不存在于Graphics.Element中。但是后来,Graphics.Element添加了一个具有微妙不同语义的rotatedImage函数(例如,您的函数使用度数,但“官方”函数使用弧度)。现在,您的代码有两个可用的rotatedImage函数……您很容易被绊倒:
{- someOtherModule.elm -}
import Graphics.Element exposing (..)

{- ... more code ... -}
someImage = rotatedImage (pi / 2) sourceImage  -- Angle is in radians

现在你需要从你的myGraphics模块中调用不同的函数,因此你需要导入它:
{- someOtherModule.elm -}
import Graphics.Element exposing (..)
import myGraphics exposing (..)

{- ... more code ... -}
someImage = rotatedImage (pi / 2) sourceImage  -- WHOOPS, angle is now in degrees!

突然间,someImage 的旋转角度发生了改变!当你导入了 myGraphics 时,你是否想要改变页面上 someImage 的外观呢?几乎肯定不是。

这就是为什么一旦你的代码相对稳定,就应该避免使用 import Foo exposing (..)。它在开发过程中非常有用,因为你不必不断地回到代码顶部来添加另一个名称到你的 import 语句中。但是一旦你完成了模块的大量开发,并且只偶尔对其进行更改,你应该真正开始使用 import Foo exposing (just, the, names, you, need)。这样你就能避免许多陷阱。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接