常量值用name = expression来定义。在 Elm 中,除了定义之外,一切都是表达式。
five = 5
six = 3 + 3
函数用name parameters... = expression来定义,多个形参之间只用空格分隔。
add number1 number2 = number1 + number2
调用函数同样是一个表达式:写出函数名,再为函数的每个形参传入实参,用空格分隔,就像定义函数时一样。
five = add 2 3
可以使用括号来指定表达式的求值顺序。
six = add 2 (1 * 4)
twelve = add 2 1 * 4
Elm 不使用大括号、圆括号或分号这类语法标记来划分代码边界,而是使用空白和缩进。
-- A function split over multiple lines, so subsequent lines must be indented
add number1 number2 =
number1 + number2
https://elmprogramming.com/indentation.html
Elm 中的每个文件都是一个模块,并且必须在所有其他代码之前包含一条module语句。
模块名必须与文件名一致,所以模块Calculator必须位于文件 Calculator.elm 中。
在模块内定义的任何内容,其作用域都是该模块私有的,除非在exposing中列出,否则无法从模块外部访问。
-- Define the Calculator module, and expose the `add` function
module Calculator exposing (add)
six = 3 + 3
add number1 number2 = number1 + number2
-- Define the Calculator module, and expose everything within: `six` and `add`
module Calculator exposing (..)
six = 3 + 3
add number1 number2 = number1 + number2
https://elm-lang.org/docs/syntax#modules
注释是 Elm 文件中不会被当作代码解释的文本,主要是给你自己和其他程序员阅读的。
单行注释有一种基于双连字符的轻量语法。
多行注释也可以用{-和-}这对起止分隔符来写。
-- a single line comment
-- another single line comment
{- a multiline comment
spawning multiple lines
-}
这里有一份风格指南,还可以使用 elm-format 自动格式化代码。
在这个练习中,你将编写一些代码,帮助你照着最喜欢的食谱做出一份美味的千层面。
你有三个任务,它们都与烹饪千层面所花的时间有关。
定义expectedMinutesInOven,计算出千层面应该在烤箱里烤多少分钟。根据食谱,在烤箱中所需的分钟数是 40:
expectedMinutesInOven
--> 40
定义preparationTimeInMinutes,它接收千层面的层数作为形参,返回准备千层面需要多少分钟,假设每层需要 2 分钟来准备。
preparationTimeInMinutes 3
--> 6
定义elapsedTimeInMinutes函数,它接收两个形参:第一个形参是千层面的层数,第二个形参是千层面在烤箱里已经烤了多少分钟。该函数应返回你烹饪千层面所花的总分钟数,也就是准备时间与千层面此刻在烤箱中已经烤过的分钟数之和。
elapsedTimeInMinutes 3 20
--> 26