gpt4 book ai didi

function - Elixir 中的命名函数和匿名函数有什么区别?

转载 作者:行者123 更新时间:2023-12-01 09:17:24 26 4
gpt4 key购买 nike

命名函数和匿名函数有什么区别?
hello = &("Hello, #{&1}")怎么样匿名函数?

最佳答案

主要区别在于范围之一。您可以在函数体中访问什么。

Elixir 中的命名函数被分组到模块中,它们的范围仅限于给它们的参数。

匿名函数可以在任何地方定义,并且可以访问其周围可见的任何内容。行话是它们是“关闭”,它们“关闭”周围的范围。

让我们看一个例子:

c = 10

anon = fn(a, b) -> a + b + c end
anon.(1, 2) # => 13, because c is available in the anonymous function

# The module below will fail to compile, because c isn't available
defmodule MyModule do
def named(a, b), do: a + b + c
end

您可以使用 & 从命名函数创建匿名函数。 capture operator ,并且它将可以访问您当前的范围。这很常见,因为许多函数都期望其他函数作为参数。浏览 the docs for Enum ,你会看到很多例子。

你会注意到我调用匿名 anon像这样的函数: anon.(1, 2) , 而不是 anon(1, 2) .它使两种函数之间的区别在您的代码中更加明确。

José 对 related question 给出了很好的回答.

关于function - Elixir 中的命名函数和匿名函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com