Elm 基本语法
前面了解了关于 Elm 的介绍与安装方法,接下来告诉你如何用 Elm 编写一个简单的Elm程序。
步骤一:在 VSCode 中创建目录 HelloApp
现在,在此目录中创建文件:Hello.elm
上图显示了项目文件夹 HelloApp 和在 VSCode 中打开的终端。
步骤二:安装必要的Elm软件包
Elm 中的软件包管理器是 elm-package 。安装 elm-lang / html 软件包。该软件包将帮助我们在浏览器中显示Elm代码的输出。
通过右键单击VSCode的“文件”→“在命令提示符中打开”,遍历到HelloApp项目文件夹。
在终端窗口中执行以下命令-
C:\Users\F2er\Elm\HelloApp> elm-package install elm-lang/html
在安装软件包时,以下文件/文件夹将添加到项目目录中。
elm-package.json(文件),存储项目元数据
elm-stuff(文件夹),存储外部包装
成功安装软件包后,将出现以下消息。
步骤三:将以下代码添加到Hello.elm文件中
-- importing Html module and the function text import Html exposing (text) -- create main method main = -- invoke text function text "Hello Elm from F2er.com"
上面的程序将在浏览器中显示来自 F2er.com 的字符串消息 Hello Elm 。
为此,我们需要在Html模块中导入函数文本。文本功能用于在浏览器中打印任何字符串值。主要方法是程序的入口点。的主要方法调用文本函数,并传递一个字符串值到它。
步骤四:编译项目
在VSCode终端窗口中执行以下命令。
elm make Hello.elm
上面命令的输出如下所示
//update path to the proj folder in the command elm make C:\Users\F2er\elm\HelloApp>elm make Hello.elm Success! Compiled 38 modules. Successfully generated index.html
上面的命令将生成一个 index.html 文件。elm编译器将.elm文件转换为JavaScript,并将其嵌入到index.html文件中。
第五步:在浏览器中打开 index.html
在任何浏览器中打开index.html文件。
Elm 注释
注释是提高程序可读性的一种方法。
注释可用于包含有关程序的其他信息,例如代码作者,有关函数构造的提示等。编译器将忽略注释。
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