Elixir 默認(rèn)參數(shù)

2023-12-14 17:21 更新

Elixir中的具名函數(shù)也支持默認(rèn)參數(shù):

defmodule Concat do
  def join(a, b, sep \\ " ") do
    a <> sep <> b
  end
end

IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world

任何表達(dá)式都可以作為默認(rèn)值,但它在函數(shù)定義時(shí)不會(huì)執(zhí)行;僅僅是存貯備用。每當(dāng)必須使用默認(rèn)值的時(shí)候,表達(dá)式才會(huì)被執(zhí)行:

defmodule DefaultTest do
  def dowork(x \\ IO.puts "hello") do
    x
  end
end
iex> DefaultTest.dowork
hello
:ok
iex> DefaultTest.dowork 123
123
iex> DefaultTest.dowork
hello
:ok

當(dāng)帶默認(rèn)值的函數(shù)有多個(gè)從句時(shí),就需要?jiǎng)?chuàng)建一個(gè)不包含函數(shù)內(nèi)容的函數(shù)頭來聲明默認(rèn)值:

defmodule Concat do
  def join(a, b \\ nil, sep \\ " ")

  def join(a, b, _sep) when is_nil(b) do
    a
  end

  def join(a, b, sep) do
    a <> sep <> b
  end
end

IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
IO.puts Concat.join("Hello")               #=> Hello

當(dāng)使用默認(rèn)值時(shí),我們要當(dāng)心函數(shù)定義的重疊:

defmodule Concat do
  def join(a, b) do
    IO.puts "***First join"
    a <> b
  end

  def join(a, b, sep \\ " ") do
    IO.puts "***Second join"
    a <> sep <> b
  end
end

如果我們將上述代碼保存到文件“concat.ex”中并編譯,Elixir將提出警告:

concat.ex:7: warning: this clause cannot match because a previous clause at line 2 always matches

編譯器告訴我們當(dāng)用兩個(gè)參數(shù)調(diào)用join函數(shù)時(shí),總會(huì)使用第一個(gè)join函數(shù)定義,而第二個(gè)定義只有當(dāng)傳遞三個(gè)參數(shù)時(shí)才會(huì)被調(diào)用:

$ iex concat.exs
iex> Concat.join "Hello", "world"
***First join
"Helloworld"
iex> Concat.join "Hello", "world", "_"
***Second join
"Hello_world"
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號