Home > Back-end >  Calling a function that's stored in a map
Calling a function that's stored in a map

Time:10-18

I'm new to Elixir, so still trying to properly understand how pattern matching works. I have a function that receives a map as an argument. This function may or may not have an icon key where icon should be a function.

  • When there's an icon key, then I'd like to call it with a value because it's a function.
  • When there's no icon key, then I'd like to have a default value.

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).

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.

Is it possible to do what I'm trying to accomplish here or is there a better way to do it?

CodePudding user response:

icon(@icon_size) is the syntax for a named function. It will look for the icon/1 named function in the current context (e. g. your current module or in your imports.)

When calling an anonymous function, you need to add a dot:

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:

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.

  • Related