defmodule FunMatch do @moduledoc """ Parameter matching for functions. Note that the oder in which functions are defined in a module matters. Matching is to the first found in order rather than to the "most specific" match. This is likely because "most specific" may be ill-defined -- ie, which is preferred when 2 of 3 match in two different ways. Author: gtowell Created: July 2022 """ @doc """ matching with 3 numeric parameters. Just take the first match so 1,1,1 will never be used """ def tst(0,0,0) do IO.puts "all zero" end def tst(2,_,_) do IO.puts "2 first" end def tst(a,b,c) do IO.puts "none match" end def tst(1,1,1) do IO.puts "all ones" end @doc """ matching with one list. Empty list can be last as it will not match to [h|r] or [a]. However a list with one item will match to [h|r] (h gets the item, r gets []) so in this ordering the fun with [a] will never get called. """ def rl([h|r]) do IO.puts "big list" end def rl([a]) do IO.puts "one item list" end def rl([]) do IO.puts "empty list" end def main() do tst(0,0,0) tst(1,1,1) tst(2,5,9) tst(42,5,8) rl([1,2,3]) rl([2]) rl([]) end end FunMatch.main