Elm - 基本语法



本章讨论如何在 Elm 中编写简单的程序。

步骤 1 - 在 VSCode 中创建一个名为 HelloApp 的目录

现在,在这个目录中创建一个文件 - **Hello.elm**。

Create directory

上图显示了在 VSCode 中打开的项目文件夹 **HelloApp** 和终端。

步骤 2 - 安装必要的 Elm 包

Elm 的包管理器是 *elm-package*。安装 *elm-lang/html* 包。此包将帮助我们显示 Elm 代码在浏览器中的输出。

在 VSCode 中右键单击“文件”→“在命令提示符中打开”,转到 **HelloApp** 项目文件夹。

在终端窗口中执行以下命令:

C:\Users\dell\Elm\HelloApp> elm-package install elm-lang/html

安装包后,项目目录中将添加以下文件/文件夹。

  • elm-package.json(文件),存储项目元数据
  • elm-stuff(文件夹),存储外部包

包成功安装后,将显示以下消息。

package installed

步骤 3 - 将以下代码添加到 Hello.elm 文件中

-- importing Html module and the function text
import Html exposing (text)

-- create main method
main =
-- invoke text function
text "Hello Elm from TutorialsPoint"

上面的程序将在浏览器中显示字符串消息 **Hello Elm from TutorialsPoint**。

为此,我们需要在 **Html** 模块中导入 **text** 函数。text 函数用于在浏览器中打印任何字符串值。main 方法是程序的入口点。main 方法调用 text 函数并将字符串值传递给它。

步骤 4 - 编译项目

在 VSCode 终端窗口中执行以下命令。

elm make Hello.elm

上述命令的输出如下所示:

//update path to the proj folder in the command elm make
C:\Users\dell\elm\HelloApp>elm make Hello.elm
Success! Compiled 38 modules.
Successfully generated index.html

上述命令将生成一个 **index.html** 文件。Elm 编译器将 .elm 文件转换为 JavaScript 并将其嵌入到 **index.html** 文件中。

步骤 5 - 在浏览器中打开 index.html

在任何浏览器中打开 *index.html* 文件。输出将如下所示:

Open browser

Elm 中的注释

注释是提高程序可读性的一种方式。注释可用于包含有关程序的其他信息,例如代码作者、关于函数构造的提示等。编译器会忽略注释。

Elm 支持以下类型的注释:

  • 单行注释 (--) - -- 和行尾之间的任何文本都被视为注释。

  • 多行注释 ({- -}) - 这些注释可以跨越多行。

示例

-- this is single line comment

{- This is a
   Multi-line comment
-}

行和缩进

Elm 没有使用大括号来指示函数定义或流程控制的代码块。代码块由行缩进表示,并且严格执行。块中的所有语句必须缩进相同的量。例如:

module ModuleIf exposing (..)
x = 0

function1 =
   if x > 5 then
      "x is greater"
   else
      "x is small"

但是,以下代码块会产生错误:

-- Create file ModuleIf.elm
module ModuleIf exposing (..)
x = 0

function1 =
   if x > 5 then
      "x is greater"
         else --Error:else indentation not at same level of if statement
      "x is small"

因此,在 Elm 中,所有使用相同空格数连续缩进的行将构成一个代码块。

C:\Users\admin>elm repl
---- elm-repl 0.18.0 -----------------------------------------------------------
   :help for help, :exit to exit, more at 
   <https://github.com/elm-lang/elm-repl>
   ---------------------------------------
   -----------------------------------------

> import ModuleIf exposing(..) -- importing module from ModuleIf.elm file
>function1 -- executing function from module
-- SYNTAX PROBLEM ---------------------------------------------------

I need whitespace, but got stuck on what looks like a new declaration. 
You are either missing some stuff in the declaration above or just need to add some spaces here:
7| else
   ^
I am looking for one of the following things:

   whitespace
广告
© . All rights reserved.