簡體   English   中英

有條件地附加到 Elixir 中的列表?

[英]Conditionally appending to a list in Elixir?

在 Python 上幾個月后,我正在研究 Elixir 代碼,而我的 memory 的慣用 ZA12EB062ECA60378 是模糊的。

此代碼有效:

# Define workers and child supervisors to be supervised
children = [
  # Start the Ecto repository
  supervisor(Ssauction.Repo, []),
  # Start the endpoint when the application starts
  supervisor(SsauctionWeb.Endpoint, []),

  supervisor(Absinthe.Subscription, [SsauctionWeb.Endpoint]),
]

children
= if System.get_env("PERIODIC_CHECK") == "ON" do
    Enum.concat(children, [worker(Ssauction.PeriodicCheck, [])])
  else
    children
  end

但我敢肯定這很尷尬。 如何用慣用的方式重寫這個?

您可以定義一個接受條件的助手 function:

defp append_if(list, condition, item) do
  if condition, do: list ++ [item], else: list
end

然后像這樣使用它:

[1,2,3]
|> append_if(true, 4)
|> append_if(false, 1000)

生產:

[1, 2, 3, 4]

看起來您正在使用已棄用的Supervisor.Spec模塊。 您可以以更現代的方式定義您的監督樹,如下所示:

children =
  [
    Ssauction.Repo,
    SsauctionWeb.Endpoint,
    {Absinthe.Subscription, [SsauctionWeb.Endpoint]}
  ]
  |> append_if(System.get_env("PERIODIC_CHECK") == "ON", Ssauction.PeriodicCheck)

盡管您可能需要修改您的子主管以實施Supervisor行為。


如果您要構建大型列表,通常會在列表前添加,然后對結果進行一次反向操作,以避免每次都遍歷整個列表:

defp prepend_if(list, condition, item) do
  if condition, do: [item | list], else: list
end

def build_list do
  []
  |> prepend_if(true, 1)
  |> prepend_if(true, 2)
  |> prepend_if(true, 3)
  |> prepend_if(false, nil)
  |> prepend_if(false, 5000)
  |> Enum.reverse()
end

你也可以這樣做;

[
  supervisor(Ssauction.Repo, []),
  supervisor(SsauctionWeb.Endpoint, []),
  supervisor(Absinthe.Subscription, [SsauctionWeb.Endpoint]),
]
|> Kernel.++(if System.get_env("PERIODIC_CHECK") == "ON" do
   [worker(Ssauction.PeriodicCheck, [])]
  else
   []
  end
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM