【问题标题】:Elixir comprehension returning a star character '*'长生不老药理解返回一个星号'*'
【发布时间】:2020-12-07 22:33:10
【问题描述】:

我有一个在 p.followings 中返回的 Persona 模型列表,我想从该模型列表中提取 followed_id 字段到一个单独的列表中。

p.followings

returns...

[
  %Poaster.Personas.Following{
    __meta__: #Ecto.Schema.Metadata<:loaded, "followings">,
    followed: %Poaster.Personas.Persona{
      __meta__: #Ecto.Schema.Metadata<:loaded, "personas">,
      background_image_url: nil,
      bio: "ASDF",
      followings: #Ecto.Association.NotLoaded<association :followings is not loaded>,
      id: 42,
      inserted_at: ~N[2020-08-14 01:52:17],
      name: nil,
      profile_image_url: nil,
      updated_at: ~N[2020-08-14 16:19:56],
      user: #Ecto.Association.NotLoaded<association :user is not loaded>,
      user_id: 1,
      username: "test"
    },
    followed_id: 42,
    id: 1,
    inserted_at: ~N[2020-08-12 20:35:09],
    persona: #Ecto.Association.NotLoaded<association :persona is not loaded>,
    persona_id: 1,
    updated_at: ~N[2020-08-12 20:35:09]
  }
]

我只是想在此处获取followed_id 的列表,这样我就可以进行查询以从我关注的那些角色中获取帖子列表。

我想找回像[42] 这样的东西。

当我执行 Enum.map(ps.followings, fn follow -&gt; follow.followed_id end) 时,这是我期望能够运行的,我回到控制台只是 '*'

当我尝试使用带有 into 选项的推导式进入一个空列表时,这也是我得到的。

persona_ids = []
for p <- p.followings, into: persona_ids, do: p.followed_id
IO.inspect(persona_ids)
[]

但是,当我使用p.followed 运行上述理解时,它会返回一个角色列表:

for p <- p.followings, into: persona_ids, do: p.followed   
[
  %Poaster.Personas.Persona{
    __meta__: #Ecto.Schema.Metadata<:loaded, "personas">,
    background_image_url: nil,
    bio: "ASDF",
    followings: #Ecto.Association.NotLoaded<association :followings is not loaded>,
    id: 42,
    inserted_at: ~N[2020-08-14 01:52:17],
    name: nil,
    profile_image_url: nil,
    updated_at: ~N[2020-08-14 16:19:56],
    user: #Ecto.Association.NotLoaded<association :user is not loaded>,
    user_id: 1,
    username: "test"
  }
]

我需要 ID 列表,而不是角色模型列表,以便我可以进行适当的 Ecto 查询以从我关注的角色中获取帖子。

这里发生了什么?我究竟做错了什么?有没有更好的方法来做我想做的事情?

【问题讨论】:

  • '*' 实际上等价于 [42],因为 42 是 * 的代码点,并且当您在 Elixir 中创建一个包含所有字符代码点的整数的列表时,您会打印出 charlist当您尝试打印它时,您应该能够正常使用该列表。尝试在该结果上执行List.first,您会看到它产生 42。
  • stackoverflow.com/questions/30037914/…你可能会在这里找到答案
  • 嗯.....这确实回答了一些问题。谢谢,@sbacarob!
  • 如果您在帖子中回答此问题,我会将其标记为已接受
  • 还要注意,在推导式中使用into: 不会影响之前声明的persona_ids 变量,因为所有变量在Elixir 中都是不可变的。

标签: elixir list-comprehension phoenix-framework ecto


【解决方案1】:

正如我在评论中提到的,以及在this other post 上讨论的那样,您收到的'*' 实际上就是您期望的列表:[42]

这是因为 42 是 * 字符的代码点(您可以通过在 iex 会话中执行 ?* 来验证这一点)。在 Elixir 和 Erlang 中,当您有一个整数列表并且所有整数都是字符的有效代码点时,它会在您使用 IO.inspect 时打印字符列表,但它是一个列表,您可以像使用任何列表。

例如,如果您在 iex 提示符中键入 [104, 101, 108, 108, 111],您将返回 'hello',但单引号表示它是一个字符列表,您可以对其执行任何您想要的列表操作。

【讨论】:

  • 一旦你提到它映射到那个字符串字符,这完全是有道理的,这对我来说只是一个非常意外的行为,所以我什至从未想过它。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多