了解Elixir函数参数中的模式匹配 [英] Understanding pattern matching in Elixir function parameters

查看:66
本文介绍了了解Elixir函数参数中的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Elixir in Action一书中,其中一个示例具有使我对模式匹配的理解加深的功能:

In the book 'Elixir in Action', one of the examples has a function that is tripping up my understanding of pattern matching:

def add_entry(
    %TodoList{entries: entries, auto_id: auto_id} = todo_list,
    entry
  ) do
    entry = Map.put(entry, :id, auto_id)
    new_entries = HashDict.put(entries, auto_id, entry)

    %TodoList{todo_list |
      entries: new_entries,
      auto_id: auto_id + 1
    }
 end

第一个参数%TodoList {entries:entry,auto_id:auto_id} = todo_list ,这本书解释说: ...此外,您保留整个 todo_list 变量中的实例

The first parameter, %TodoList{entries: entries, auto_id: auto_id} = todo_list, the book explains "...Furthermore, you keep the entire instance in a todo_list variable"

这使我感到困惑,因为我认为变量绑定在 ='模式匹配运算符。有人可以帮助解释第一个参数发生了什么以及传入的值如何在函数体内使用吗?

This confuses me because I thought variables get bound on the left side of a '=' pattern matching operator. Could someone help explain what is happening with the first parameter and how the incoming values are able to be used inside the function body?

推荐答案




我认为变量绑定在'='模式匹配运算符的左侧

I thought variables get bound on the left side of a '=' pattern matching operator

是正确的,在这种情况下,条目 auto_id 变量是绑定的。右侧 todo_list 从参数绑定到函数。

That's correct, in this case the entries and auto_id variables are bound. The right-hand side todo_list is bound from the argument to the function.

就像这样做:

iex(1)> foobar = %{foo: "foo", bar: "bar"}
%{bar: "bar", foo: "foo"}
iex(2)> %{foo: matched} = foobar
%{bar: "bar", foo: "foo"}
iex(3)> matched
"foo"

在函数签名中执行此操作的唯一区别是

The only difference when doing it in a function signature is that the first step of defining what becomes the right-hand-side is handled automatically.

正如书中所述,您可以定义如下函数签名:

As the book says, you can define a function signature like this:

def do_something_with_foo(%{foo: matched} = original)

上面已经解释了,其中匹配原始在功能正文中可用。如果仅 在乎匹配的值,则可以省略右侧:

Which is explained above, where both matched and original are available in the function body. If you only care about the matched values, you can omit the right-hand side:

def do_something_with_foo(%{foo: matched})

在这种情况下,仅匹配的值已匹配将可用。匹配仍然发生,但是作为第一个参数传递给隐式用作右侧函数的数据结构,就好像您已使用 = 一样,绑定到变量。

In this case, only the matched value matched will be available. The match still happens, but the data structure passed as the first argument to the function that is used implicitly as the right-hand side, as if you had used =, is not bound to a variable.

这篇关于了解Elixir函数参数中的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆