什么`揭露(..)`在榆树中意味着什么?

Ter*_*non 14 elm

我试图理解第一个榆树的例子,它有这个:

import Graphics.Element exposing (..)

什么exposing (..)意思?

Gre*_*age 14

exposing(..)允许您直接调用函数.例如,如果SamplePackage具有函数x和y,则exposing (..)可以调用SamplePackage.x和SamplePackage.y,同时 import SamplePackage可以调用x和y而不指定其包含的包.

  • 如果您使用此语法导入两个包并且它们都有方法'X'会发生什么? (4认同)

kaz*_*kaz 8

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

import Graphics.Element exposing (Element, show)
Run Code Online (Sandbox Code Playgroud)

它仍然适用于这个例子.


rmu*_*unn 5

这是一个老问题,但无论如何我会以另一种方式回答这个问题,exposing (..)并解释一下为什么它通常是一个坏主意.如果你有Python编程的背景知识,那么你可以把它想象成from module import *Python.这个榆树代码:

import Graphics.Element exposing (Element, show)
Run Code Online (Sandbox Code Playgroud)

在Python中看起来像这样:

from Graphics.Element import Element, show
Run Code Online (Sandbox Code Playgroud)

而这个榆树代码:

import Graphics.Element exposing (..)
Run Code Online (Sandbox Code Playgroud)

在Python中看起来像这样:

from Graphics.Element import *
Run Code Online (Sandbox Code Playgroud)

前两个只会添加名称Elementshow当前模块的命名空间; 后两个示例将所有名称添加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
Run Code Online (Sandbox Code Playgroud)

现在您需要一个与myGraphics模块不同的功能,因此您可以导入它:

{- someOtherModule.elm -}
import Graphics.Element exposing (..)
import myGraphics exposing (..)

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

突然轮换了someImage!导入时myGraphics,您是否打算更改someImage页面上的显示方式?几乎肯定不是.

这就是为什么import Foo exposing (..)一旦你的代码相对稳定就应该避免原因.它在开发中非常有用,因为您不必经常回到代码的顶部为您的import语句添加另一个名称.但是,一旦你完成你的模块上做比较大的发展,你就只能做它偶尔会有变化,你真的应该切换到使用import Foo exposing (just, the, names, you, need).你会以这种方式躲避许多陷阱.