Elm - 变量

根据定义,变量是存储值的"内存中的命名空间"。 换句话说,它充当程序中值的容器。 变量帮助程序存储和操作值。

Elm 中的变量与特定的数据类型相关联。 数据类型决定变量内存的大小和布局、内存中可以存储的值的范围以及可以对变量执行的操作集。

变量命名规则

在本节中,我们将了解变量命名规则。

  • 变量名称可以由字母、数字和下划线字符组成。
  • 变量名称不能以数字开头。 它必须以字母或下划线开头。
  • 大小写字母不同,因为 Elm 区分大小写。

Elm 中的变量声明

下面给出了 Elm 中声明变量的类型语法 −

语法 1

variable_name:data_type = value

":" 语法(称为类型注释)用于将变量与数据类型关联起来。

语法 2

variable_name = value-- no type specified

在 Elm 中声明变量时,数据类型是可选的。 在这种情况下,变量的数据类型是根据分配给它的值推断出来的。

示例

此示例使用 VSCode 编辑器编写 elm 程序并使用 elm repl 执行它。

步骤 1 − 创建一个项目文件夹 - VariablesApp。 在项目文件夹中创建一个 Variables.elm 文件。

将以下内容添加到文件中。

module Variables exposing (..) //Define a module and expose all contents in the module
message:String -- type annotation
message = "Variables can have types in Elm"

程序定义了一个模块变量。 模块的名称必须与 elm 程序文件的名称相同。 (..) 语法用于公开模块中的所有组件。

程序声明了一个String类型的变量消息。

插图

步骤 2 − 执行程序。

  • 在 VSCode 终端中键入以下命令以打开 elm REPL。
elm repl
  • 在 REPL 终端中执行以下 elm 语句。
> import Variables exposing (..) --imports all components from the Variables module
> message --Reads value in the message varaible and prints it to the REPL 
"Variables can have types in Elm":String
>

示例

使用 Elm REPL 尝试以下示例。

C:\Users\dell\elm>elm repl
---- elm-repl 0.18.0 ---------------------------------------
--------------------
:help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl>
-------------------------------------
------------------------------------------
> company = "TutorialsPoint"
"TutorialsPoint" : String
> location = "Hyderabad"
"Hyderabad" : String
> rating = 4.5
4.5 : Float

这里,变量 company 和 location 是 String 变量, rating 是 Float 变量。

elm REPL 不支持变量的类型注释。 如果声明变量时包含数据类型,以下示例将引发错误。

C:\Users\dell\elm>elm repl
---- elm-repl 0.18.0 -----------------------------------------
------------------
:help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl>
----------------------------------------
----------------------------------------
> message:String
-- SYNTAX PROBLEM -------------------------------------------- repl-temp-000.elm

A single colon is for type annotations. Maybe you want :: instead? Or maybe you
are defining a type annotation, but there is whitespace before it?

3| message:String
^

Maybe <http://elm-lang.org/docs/syntax> can help you figure it out.

要在使用 elm REPL 时插入换行符,请使用 \ 语法,如下所示−

C:\Users\dell\elm>elm repl
---- elm-repl 0.18.0 --------------------------------------
---------------------
:help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl>
------------------------------------------
--------------------------------------
> company \ -- firstLine
| = "TutorialsPoint" -- secondLine
"TutorialsPoint" : String