Elixir语法 - 定义具有相似签名且没有end关键字的多个函数

问题描述 投票:0回答:2

我正在查看来自https://github.com/shamshirz/scoreboard/blob/master/lib/scoreboard/games/games.ex的示例应用程序

我遇到了以下代码,我根据自己的理解对其进行了标记。

def query(Score, params) do #defined function query/2
    params
    |> Map.put_new(:limit, 10) #adding to the "dictionary"
    |> Map.put_new(:order, :total) #""
    |> Map.to_list() #flattening out the map
    |> Enum.reduce(Score, &apply_param/2) #call apply_param/2 for each item
  end

#defines query/2... now we have two query/2... Wait, how is this?
#I guess this one is query/2 with a private argument (_params). 
#Also, this doesnt have an `end`
  def query(queryable, _params), do: queryable 

#defines apply_param/2 with no end
  def apply_param({:limit, num}, queryable), do: queryable |> limit(^num) 

#defines another apply_param/2, no end again!
  def apply_param({:order, field}, queryable), do: queryable |> order_by(desc: ^field)

#defines another apply_param/2, no end again!...
  def apply_param({:player_id, player_id}, queryable),
    do: queryable |> where(player_id: ^player_id)

#again...
  def apply_param(_param, queryable), do: queryable

#finally a function I can read (I think)
#take in a query and execute, if its null -> error, result -> return with :ok
  def get(queryable, id) do
    case Repo.get(queryable, id) do
      nil ->
        {:error, :not_found}

      result ->
        {:ok, result}
    end
  end
  #look at those nice "end"-ings

什么是apply_param定义?为什么他们没有end,他们怎么都有看似相似的签名? I.E.他们接受tuple和第二个queryable变量?

elixir
2个回答
© www.soinside.com 2019 - 2024. All rights reserved.