简体   繁体   English

调用存储在 map 中的 function

[英]Calling a function that's stored in a map

I'm new to Elixir, so still trying to properly understand how pattern matching works.我是 Elixir 的新手,所以仍在尝试正确理解模式匹配的工作原理。 I have a function that receives a map as an argument.我有一个 function 接收map作为参数。 This function may or may not have an icon key where icon should be a function .这个 function 可能有也可能没有icon键,其中icon应该是function

  • When there's an icon key, then I'd like to call it with a value because it's a function.当有一个icon键时,我想用一个值来调用它,因为它是一个 function。
  • When there's no icon key, then I'd like to have a default value.当没有icon键时,我想要一个默认值。

I thought the code below would work but it didn't:我认为下面的代码可以工作,但它没有:

defp get_icon(%{:icon => icon}), do: icon(@icon_size)
defp get_icon(_), do: Icon.default_icon(@icon_size)

When I try to call icon(@icon_size) , I get the following error message: undefined function icon/1 (expected HelloWeb.Components.Button to define such a function or for it to be imported, but none are available) .当我尝试调用icon(@icon_size)时,我收到以下错误消息: undefined function icon/1 (expected HelloWeb.Components.Button to define such a function or for it to be imported, but none are available)

I thought maybe I needed to pass the arity to icon like this: &icon/1 but, then, I got another error saying & is not allowed in matches .我想也许我需要像这样将 arity 传递给icon&icon/1但是,然后,我得到另一个错误,说& is not allowed in matches

Is it possible to do what I'm trying to accomplish here or is there a better way to do it?是否有可能做我在这里想要完成的事情,或者有更好的方法吗?

icon(@icon_size) is the syntax for a named function. icon(@icon_size)是命名 function 的语法。 It will look for the icon/1 named function in the current context (eg your current module or in your imports.)它将在当前上下文中查找名为 function 的icon/1 (例如,您当前的模块或在您的导入中。)

When calling an anonymous function, you need to add a dot:在调用匿名 function 时,需要加一个点:

icon.(@icon_size)

The capture operator & is to take a named function and make an anonymous function from it, so this is the opposite of what you wanted to achieve here:捕获运算符&将获取一个名为 function 并从中创建一个匿名 function ,所以这与您想要在这里实现的相反:

f = &String.upcase/1
# is the same as
f = fn x -> String.upcase(x) end

You can see more information in the Function module documentation or the getting started guide .您可以在Function模块文档入门指南中查看更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM