Elm 变量
根据定义,变量是“存储在内存中的命名空间”。换句话说,它充当程序中值的容器,变量有助于程序存储和操纵值。
Elm 中的变量与特定的数据类型相关联。数据类型确定变量的内存大小和布局,可以存储在该内存中的值的范围以及可以对该变量执行的一组操作。
Elm 变量命名规则
在本章节中,我们将学习 Elm 变量命名规则。
变量名称可以由字母,数字和下划线字符组成。
变量名不能以数字开头。它必须以字母或下划线开头。
由于 Elm 区分大小写,因此大写字母和小写字母是不同的。
Elm 变量声明
在 Elm 中声明变量的类型语法如下:
语法1
variable_name:data_type = value
语法(称为类型注释):“:”用于将变量与数据类型相关联。
语法2
variable_name = value-- no type specified
在 Elm 中声明变量时,数据类型是可选的。在这种情况下,将从分配给变量的值中推断出变量的数据类型。
示例
本示例使用VSCode编辑器编写elm程序,并使用elm repl执行它。
步骤一:创建一个项目文件夹: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 的变量消息。
步骤二:执行程序。
在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\F2er.com\elm>elm repl ---- elm-repl 0.18.0 --------------------------------------- -------------------- :help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl> ------------------------------------- ------------------------------------------ > company = "F2er.com" "F2er.com" : String > location = "China" "China" : String > rating = 4.5 4.5 : Float
在这里,变量company和location是String变量,而rating是Float变量。
elm REPL不支持变量的类型注释。
如果声明变量时包含数据类型,则以下示例将引发错误。
C:\Users\F2er.com\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\F2er.com\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 | = "F2er.com" -- secondLine "F2er.com" : String