Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have default and optional arguments?

Tags:

elixir

I have this function

    def start(data, opts \\ [pages: 17, depth: 3]) do
        maxPages = opts[:pages]
        maxDepth = opts[:depth]
        IO.puts maxPages
        IO.puts maxDepth
    end

When I do Program.start("data", pages: 8) then I want it to print 8 and 3 but it only prints 8

like image 863
MikeC Avatar asked Apr 05 '16 17:04

MikeC


1 Answers

You could go with Keyword#get/3 instead, like:

def start(data, opts \\ []) do
    maxPages = Keyword.get(opts, :pages, 17)
    maxDepth = Keyword.get(opts, :depth, 3)
    IO.puts maxPages
    IO.puts maxDepth
end

Or alternatively, Keyword#merge/2 pass in opts with some defaults:

def start(data, opts \\ []) do
    finalOpts = Keyword.merge([pages: 17, depth: 3], opts)
    maxPages = finalOpts[:pages]
    maxDepth = finalOpts[:depth]
    IO.puts maxPages
    IO.puts maxDepth
end

Hope it helps!

like image 174
Paweł Dawczak Avatar answered Oct 07 '22 02:10

Paweł Dawczak