2016-04-05 21 views
6

Ben o zaman Program.start("data", pages: 8) yaptığınızdaVarsayılan ve isteğe bağlı argümanlar nasıl alınır?

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

Ben 8 ve 3 yazdırmak istediğiniz bu fonksiyonu var ama sadece gibi 8

cevap

12

yerine Keyword#get/3 ile gidebiliriz yazdırır:

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

Ya da alternatif olarak,opts bazı def ile geçirin aults:

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 

Umut eder! yerine kelime listesinin haritası ile

0

Bence daha güzel/daha kompakt:

defmodule U2 do 
    def format(value, opts \\ %{}) do 
    opts = %{unit: "kg", decimals: 2} |> Map.merge(opts) 
    "#{Float.to_string(value, [decimals: opts.decimals])} #{opts.unit}" 
    end 
end 
IO.inspect U2.format 3.1415       # "3.14 kg" 
IO.inspect U2.format 3.1415, %{decimals: 3}   # "3.142 kg" 
IO.inspect U2.format 3.1415, %{decimals: 3, unit: "m"} # "3.142 m" 
IO.inspect U2.format 3.1415, %{unit: "Pa"}    # "3.14 Pa" 
İlgili konular