【问题标题】:Compare two lists with elixir return true if match如果匹配,则使用 elixir 比较两个列表返回 true
【发布时间】:2017-12-10 10:30:23
【问题描述】:

我有这个功能:我正在尝试与记录列表进行比较,以查看两者之间是否匹配。

def current_user_has_team?(user, teams) do
  user = user |> Repo.preload(:teams)

  Enum.member?(user.teams, teams)
end

这不起作用,因为当只有一条记录并且它们匹配时它会返回 false。

我怎么说:“看看这个记录列表,这些记录中的任何一个在另一个列表中匹配吗?”在 Elixir 中?

在 Ruby 中应该是这样的:

list_1 = [1,2,3]
list_2 = [3,4,5]

(list_1 & list_2).any? => true

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    要回答原始问题,您可以这样做:

    Enum.any?(user.teams, fn team -> team in teams end)
    

    但更好的方法是使用不同的查询 - 检查teams 中是否存在user.teams 中的任何id

    def current_user_has_team?(user, teams) do
      ids = Enum.map(teams, & &1.id)
      !!Repo.one(from(team in assoc(user, :teams), where: team.id in ^ids, limit: 1))
    end
    

    如果没有匹配,查询将返回nil,如果有,则返回第一个匹配的团队。 !! 会将其转换为布尔值,这将使匹配返回 true 和不匹配返回 false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多