您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Elm 变量

根据定义,变量是“存储在内存中的命名空间”。换句话说,它充当程序中值的容器,变量有助于程序存储和操纵值。

Elm 中的变量与特定的数据类型相关联。数据类型确定变量的内存大小和布局,可以存储在该内存中的值的范围以及可以对该变量执行的一组操作。

Elm 变量命名规则

在本章节中,我们将学习 Elm 变量命名规则。

变量可以由字母,数字和下划线字符组成。

变量名不能以数字开头。它必须以字母或下划线开头。

由于 Elm 区分大小写,因此大写字母和小写字母是不同的。

Elm 变量声明

在 Elm 中声明变量的类型语法如下:

variable_name:data_type = value

语法(称为类型注释):“:”用于将变量与数据类型相关联。

variable_name = value-- no type specified

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

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

将以下到中。

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
>  = 4.5
4.5 : Float

,变量company和location是String变量,而是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
--  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/> can help you ure 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

联系我
置顶