I'm learning Elixir.
while building a trivial cli application (as seen here http://asquera.de/blog/2015-04-10/writing-a-commandline-app-in-elixir/) I'm defining a module that implements a main/1
function that accepts a List
as an argument.
My question is: What is the best way to pattern match a method against a non-empty list ?
This is what i did and it seems to work but i was wondering if the elixir community has better suggestions ( maybe def main(args) when is_list(args) and length(args) > 0 do
is considered better ? )
defmodule Cli do
def main([]) do
IO.puts "arguments are needed"
end
def main([_|_] = args) do
options = parse_args(args)
input = options[:name]
size = options[:size]
output(input, size)
end
def parse_args(args) do
{options, _, _} = OptionParser.parse args,
switches: [name: :string, size: :integer]
options
end
def output() do
IO.puts "Missing required --name parameter"
end
def output(input) do
# defaulting size to 50
output(input, 50)
end
def output(input, block_size) do
IO.puts "you entered #{input} and #{block_size}"
end
end
def main([_|_] = args) do
</joke> \$\endgroup\$cmd --foo bar
, args will be["foo", "bar"]
if you callcmd
args will be[]
) \$\endgroup\$