Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

undefined function error when pattern matching

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

icon(@icon_size) is the syntax for a named function. It will look for the icon/1 named function in 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading