Elm 语言入门笔记
Elm 是一门函数式编程语言。
安装和使用
在线编辑器:Try Elm! (elm-lang.org) 输入代码后,点击编辑器右下角即可编译运行。
模块
import Html exposing (text)
greet name =
"hello, " ++ name ++ "!"
main =
text (greet "world!")
上面的代码等价于:
import Html
greet name =
"hello, " ++ name ++ "!"
main =
Html.text (greet "world!")
可以看到 import Html
可以导入 Html
这个名称。exposing
可以将 Html
下的名称直接暴露出来,方便我们不加 Html
就直接调用。
如果要暴露 Html
下的所有名称:
import Html exposing (..)
另外检查元素可以看到:
<body>
hello, world!!
...
</body>
这说明 text
函数的作用类似 PHP 的 echo
或者 C 的 puts
,直接输出文本。
函数
从上面的例子不难看出,函数如此定义:
funcName arg1 arg2 ... =
statement
调用:
funcName arg1 arg2 ...
列表
import Html exposing(..)
import Html.Attributes exposing (..)
greet name =
"hello, " ++ name ++ "!"
main =
div [class "hello"]
[
b [] [text (greet "world")]
]
效果:
<div class="hello"><b>hello, world!</b></div>
这里的方括号用于创建列表。
可以看到,div
函数的两个实参分别是 [class"hello"]
和 [b [] [text (greet"world")]]
字符串连接:
> "butter" ++ "fly"
"butterfly"
元组
(True, "name accepted!")
分支语句
if String.length name <= 20 then
(True, "name accepted!")
else
(False, "name was too long; please limit it to 20 characters")
|
记录
john = { age = 81, first = "John", last = "Hobson" }
访问字段
第一种方式:
john.last
第二种方式:将 .last
作为函数:
.last john
List.map .last [john,john,john]
基于记录创建新记录
{ john | last = "Adams" }