true 有没有办法使-6ren">
gpt4 book ai didi

enums - Elixir 枚举成员?对于多个元素

转载 作者:行者123 更新时间:2023-12-01 08:50:04 27 4
gpt4 key购买 nike

Enum.member/2只能检查一个元素成员资格。喜欢
Enum.member ["abc", "def", "ghi", "123", "hello"], "abc" -> true
有没有办法使用匿名函数等来检查多个项目的成员资格,如果不包含其中一个元素以保持 DRY 并避免此类情况,则返回 false ?

Enum.member ["abc", "def", "ghi", "123", "hello"], "abc"
Enum.member ["abc", "def", "ghi", "123", "hello"], "def"
Enum.member ["abc", "def", "ghi", "123", "hello"], "ghi"

最佳答案

您可以使用 Enum.all?/2 的组合(如果您希望所有项目都存在)或 Enum.any?/2 (如果您想要任何一项存在)+ Enum.member?/2 (或 in 运算符,其作用相同):

iex(1)> list = ["abc", "def", "ghi", "123", "hello"]
["abc", "def", "ghi", "123", "hello"]
iex(2)> Enum.all?(["abc", "def", "ghi"], fn x -> x in list end)
true
iex(3)> Enum.any?(["abc", "def", "ghi"], fn x -> x in list end)
true
iex(4)> Enum.all?(["abc", "z"], fn x -> x in list end)
false
iex(5)> Enum.any?(["abc", "z"], fn x -> x in list end)
true

关于enums - Elixir 枚举成员?对于多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44706839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com