Elm-variables

提供:Dev Guides
移動先:案内検索

エルム-変数

定義により、変数は値を格納する「メモリ内の名前付きスペース」です。 つまり、プログラムの値のコンテナとして機能します。 変数は、プログラムが値を保存および操作するのに役立ちます。

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 = "finddevguides"
"finddevguides" : String
> location = "Hyderabad"
"Hyderabad" : String
> rating = 4.5
4.5 : Float

ここで、変数companyおよびlocationは文字列変数であり、評価はフロート変数です。

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
| = "finddevguides" -- secondLine
"finddevguides" : String