首页 > 解决方案 > Elixir 功能评估

问题描述

Elixir 语言的新手,我绝对欣赏简洁的语法和强大的运行时环境。

下面的简单问题是在什么情况下会重新评估 get_horizo​​ntal_line() 函数?

当我学习这门语言时,我遇到的更广泛的问题是关于执行环境和编译器优化。我正在慢慢阅读 Elixir 文档,接下来我计划阅读 Erlang 文档,然后我正在寻找有关运行时环境 (VM) 的信息。

有没有人建议去哪里了解更多关于 VM 系统架构和编译器的信息?在我查看 Erlang VM 源代码之前。

def get_horizontal_line, do: String.duplicate("-", 80)
def get_horizontal_line(n), do: String.duplicate("-", n)

# Binds the result of calling the function but does not execute it to determine the result.
x = get_horizontal_line()
y = get_horizontal_line()

# Forces evaluation of the function.
IO.puts(x)

# Does this force re-evaluation?
IO.puts(y)

# Binds the result of calling the function but does not execute it to determine the result.
x = get_horizontal_line(80)
y = get_horizontal_line(80)

# Forces evaluation of the function.
IO.puts(x)

# Does this force re-evaluation?
IO.puts(y)

标签: elixir

解决方案


def get_horizo​​ntal_line, do: String.duplicate("-", 80) def get_horizo​​ntal_line(n), do: String.duplicate("-", n)

这用一个子句定义了两个函数。第一个函数不带参数,第二个函数带一个。

# Binds the result of calling the function but does not execute it to determine the result.
x = get_horizontal_line()
y = get_horizontal_line()

这两个表达式都计算对 的函数调用get_horizontal_line。所以我不确定你所说的“不执行”是什么意思。Elixir 中没有惰性求值。此时该get_horizontal_line函数已被调用并执行了两次。

# Forces evaluation of the function.
IO.puts(x)

变量x已经绑定到get_horizontal_line()上面的结果,所以这只是打印它的值。

# Does this force re-evaluation?
IO.puts(y)

变量y已经绑定到get_horizontal_line()上面的结果,所以这只是打印它的值。

# Binds the result of calling the function but does not execute it to determine the result.
x = get_horizontal_line(80)
y = get_horizontal_line(80)

# Forces evaluation of the function.
IO.puts(x)

# Does this force re-evaluation?
IO.puts(y)

这与上面的行为相同。

我不知道这是否回答了你的问题。

关于更多关于 Erlang VM 的学习,强烈推荐 BEAM 书并且是免费的[1]。

[1] https://github.com/happi/theBeamBook


推荐阅读