elixir - Elixir 功能评估
问题描述
Elixir 语言的新手,我绝对欣赏简洁的语法和强大的运行时环境。
下面的简单问题是在什么情况下会重新评估 get_horizontal_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)
解决方案
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()
这两个表达式都计算对 的函数调用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]。
推荐阅读
- html - 如何在Angular中的对象中数据绑定对象数组?
- python - 将信号连接到插槽会产生 (nullptr)::slot() 错误
- reactjs - 使用 react-testing-library 测试样式化的组件
- r - 在 for 循环中失败 gsub
- javascript - javascript中firestore中的orderBy()
- python - 如何使用 qtDesigner 在 pyqt5 的 MDI 区域中停靠子窗口
- swift - 如何修复 IBOutlet 连接与 main.storyboard 错误?
- excel - 在网页上提交数据后查询未重定向到原始 URL
- qt - 在 eglfs 模式下,来自主题的图标在 QML 中不起作用
- javascript - 意外的节点类型:预期类型时发现 EXPR:LABELED_ARG