0
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ <joke>I find this piece of code offensive: def main([_|_] = args) do</joke> \$\endgroup\$ – Grajdeanu Alex. Jan 11 '17 at 15:39
  • 3
    \$\begingroup\$ The question looks a bit sketchy. What arguments do you expect, and what do they mean? \$\endgroup\$ – 200_success Jan 11 '17 at 15:53
  • \$\begingroup\$ args should be a list of command line arguments (es if you call cmd --foo bar, args will be ["foo", "bar"] if you call cmd args will be []) \$\endgroup\$ – G3z Jan 11 '17 at 16:05
  • \$\begingroup\$ @Dex'ter my question is: how would you rewrite that? \$\endgroup\$ – G3z Jan 11 '17 at 16:09
  • \$\begingroup\$ As stands, if this question were open, I think it would be closed as stub code from ` # do stuff with args`. There may not be much happening in your trivial application, but there is more than you show here. \$\endgroup\$ – mdfst13 Jan 12 '17 at 11:19
2
\$\begingroup\$

You've implemented it by pattern matching against empty lists with def main([]). If an empty list is passed to main, it will be caught here. In the second def main(args), args should never be an empty list.

If you want to make sure that args is a list, you could use a guard clause: def main(args) when is_list(args). (You should then write a catch-all third definition: def main(_)).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.