Red Baron
Red Baron

Reputation: 7642

How to pass maps to functions in elixir?

I'm iterating over a list with the structure

[
  %{color: "green", index: 0},
  %{color: "blue", index: 1}
]

and I want to pass this to a function but I getting errors saying: no function clause matching

def myFunction(%{color: color, index: index}) do
  IO.inspect(color)
end

what am i doing wrong to pattern match on this?

Upvotes: 0

Views: 760

Answers (2)

7stud
7stud

Reputation: 48599

what am i doing wrong to pattern match on this?

You defined your function to take a map as the single argument:

def myFunction(%{color: color, index: index}) do

yet the data structure you listed in your post is...a list:

[
  %{color: "green", index: 0},
  %{color: "blue", index: 1}
]

A list is not a map, and because you did not define any function clause that takes a list as an argument, you cannot past a list to the function.

You could do this:

a.ex:

defmodule A do
  def go do
    colors = [
      %{color: "green", index: 0},
      %{color: "blue", index: 1}
    ]

    display(colors)
  end

  def display([rgb|rest]) do
    IO.puts "color is: #{rgb.color}"
    display(rest)
  end
  def display([]) do
    :ok
  end

end

In iex:

iex(4)> c("a.ex")
[A]

iex(5)> A.go     
color is: green
color is: blue
:ok

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You are doing everything right, assuming you pass each element of the list to the function, not the whole list. That might be done, e. g. by iteration through list elements as shown below.

defmodule M do
  @data [%{color: "green", index: 0}, %{color: "blue", index: 1}]
  
  def my_function(%{color: color, index: index}) do
    IO.inspect(color)
  end
  
  def test, do: Enum.each(@data, &my_function/1)
end

And then

M.test

"green"
"blue"

Sidenote: in we use snakecase, not camelcase for naming.

Upvotes: 1

Related Questions