Skip to content

Elixir Kernel & Enum API

Elixir Kernel and Enum modules providing IO, string, collection and process-related functions.

1 class · 8 methods

Kernel & Enum

8 methods

Elixir Kernel 与 Enum 核心函数集合。

IO.puts(string)

向标准输出打印字符串并换行。

Parameters

NameTypeDescription
stringString.t() / chardata待打印内容

Returns

:ok

Example

elixir
IO.puts("Hello, Elixir")
IO.puts("line 1\nline 2")
String.length(s)

返回字符串的 Unicode 字符数(非字节数)。

Parameters

NameTypeDescription
sString.t()字符串

Returns

non_neg_integer,字符数

Example

elixir
String.length("hello")   # 5
String.length("中文")     # 2
String.split(s, pattern)

按模式将字符串分割为列表。

Parameters

NameTypeDescription
sString.t()源字符串
patternString.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

NameTypeDescription
enumerableEnumerable.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

NameTypeDescription
enumerableEnumerable.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

NameTypeDescription
enumerableEnumerable.t()可枚举对象
accany初始累加值
fun(element, acc -> acc)归约函数

Returns

any,最终累加值

Example

elixir
Enum.reduce([1, 2, 3, 4], 0, fn x, acc -> acc + x end)
# 10
Map.new(pairs) / Map.put(map, key, value)

创建映射或在已有映射中插入键值对。

Parameters

NameTypeDescription
mapmap()映射(put 时)
keyany
valueany

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

NameTypeDescription
fun(-> any)进程入口函数

Returns

pid,新进程标识符

Example

elixir
pid = spawn(fn -> IO.puts("running in process") end)
# 同步输出: running in process

Process.alive?(pid)