Kernel & Enum
8 methodsElixir Kernel 与 Enum 核心函数集合。
IO.puts(string)向标准输出打印字符串并换行。
Parameters
| Name | Type | Description |
|---|---|---|
| string | String.t() / chardata | 待打印内容 |
Returns
:ok
Example
elixir
IO.puts("Hello, Elixir")
IO.puts("line 1\nline 2")String.length(s)返回字符串的 Unicode 字符数(非字节数)。
Parameters
| Name | Type | Description |
|---|---|---|
| s | String.t() | 字符串 |
Returns
non_neg_integer,字符数
Example
elixir
String.length("hello") # 5
String.length("中文") # 2String.split(s, pattern)按模式将字符串分割为列表。
Parameters
| Name | Type | Description |
|---|---|---|
| s | String.t() | 源字符串 |
| pattern | String.t() / Regex.t() | 分割模式 |
Returns
[String.t()],分割后的字符串列表
Example
elixir
String.split("a,b,c", ",")
# ["a", "b", "c"]
String.split("hello world", " ")
# ["hello", "", "world"]Enum.map(enumerable, fun)对可枚举对象每个元素应用函数,返回新列表。
Parameters
| Name | Type | Description |
|---|---|---|
| enumerable | Enumerable.t() | 可枚举对象 |
| fun | (element -> any) | 映射函数 |
Returns
list,映射结果列表
Example
elixir
Enum.map([1, 2, 3], fn x -> x * 2 end)
# [2, 4, 6]
Enum.map([1, 2, 3], &(&1 * 10))
# [10, 20, 30]Enum.filter(enumerable, fun)保留满足谓词的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| enumerable | Enumerable.t() | 可枚举对象 |
| fun | (element -> boolean) | 谓词函数 |
Returns
list,过滤后的列表
Example
elixir
Enum.filter([1, 2, 3, 4], fn x -> rem(x, 2) == 0 end)
# [2, 4]Enum.reduce(enumerable, acc, fun)将可枚举对象归约为单个累计值。
Parameters
| Name | Type | Description |
|---|---|---|
| enumerable | Enumerable.t() | 可枚举对象 |
| acc | any | 初始累加值 |
| fun | (element, acc -> acc) | 归约函数 |
Returns
any,最终累加值
Example
elixir
Enum.reduce([1, 2, 3, 4], 0, fn x, acc -> acc + x end)
# 10Map.new(pairs) / Map.put(map, key, value)创建映射或在已有映射中插入键值对。
Parameters
| Name | Type | Description |
|---|---|---|
| map | map() | 映射(put 时) |
| key | any | 键 |
| value | any | 值 |
Returns
map,新建或更新后的映射
Example
elixir
Map.new([{:a, 1}, {:b, 2}])
# %{a: 1, b: 2}
Map.put(%{a: 1}, :b, 2)
# %{a: 1, b: 2}spawn(fun)创建一个新进程执行给定函数,返回进程 PID。
Parameters
| Name | Type | Description |
|---|---|---|
| fun | (-> any) | 进程入口函数 |
Returns
pid,新进程标识符
Example
elixir
pid = spawn(fn -> IO.puts("running in process") end)
# 同步输出: running in process
Process.alive?(pid)