Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching Elixir Record Aganist Struct

Is there a way to pattern match a record against a struct? E.g given a record and a struct below.

struct = %User{name: "", twitter:""}
record = {User, "mossplix ", "@mossplix"}
like image 844
mossplix Avatar asked May 28 '15 02:05

mossplix


1 Answers

You either need to match the fields manually

defmodule Test do
  def foo(%User{name: name, twitter: twitter}, {User, name, twitter}) do
    IO.puts "match :)"
  end

  def foo(_struct, _record) do
    IO.puts "no match :("
  end
end

or you need to convert it to a struct first and then match the two

defmodule Test do
  def foo(struct, record) do
    do_foo struct, user_record_to_struct(record)
  end

  defp user_record_to_struct({User, name, twitter}) do
    %User{name: name, twitter: twitter}
  end

  defp do_foo(struct, struct) do
    IO.puts "match :)"
  end

  defp do_foo(_struct1, _struct2) do
    IO.puts "no match :("
  end
end
like image 72
Patrick Oscity Avatar answered Oct 14 '22 19:10

Patrick Oscity