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"

該程式定義了一個名為 Variables 的模組。模組的名稱必須與 elm 程式檔案的名稱相同。(..)語法用於公開模組中的所有元件。

該程式聲明瞭一個型別為String的變數 message。

Illustration

步驟 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
廣告