使用结构Elixir更新List

时间:2017-07-07 01:31:09

标签: elixir phoenix-framework

我有一个对象

%{
  shares: []
}

我想通过%Cs{name: "Junaid1"}%Cs{name: "Junaid2"}将结构Enum.eachmap添加到列表中,是否可以这样做?

好的,只是更简短,我再次更新问题..

 Enum.each(email_array, fn (email) ->
    with {:found_user, sharee} <- ensure_user(email)
    do
      case CameraShare.create_share(camera, sharee, caller, params["rights"], params["message"]) do
        {:ok, camera_share} ->
           #Add camera_share to list
        {:error, changeset} ->
          #Add error to a list
      end
    else
      {:not_found, email} ->
        case CameraShareRequest.create_share_request(camera, email, caller, params["rights"], params["message"]) do
          {:ok, camera_share_request} ->
            #Add camera_share to list
          {:error, changeset} ->
            #Add error to list
        end
    end
  end)

然后在Enum.each的末尾..将会有一张地图

%{
   shares: [all shares],
   errors: [all errors]
}

其中每个共享的类型为%CameraShare{__meta__: #Ecto.Schema.Metadata<:loaded, "camera_shares">}

2 个答案:

答案 0 :(得分:1)

map = %{
  shares: [%{name: "Junaid0"}]
}
add_shares = [%{name: "Junaid1"}, %{name: "Junaid2"}]

Straigt list concatenation

%{map | shares: map[:shares] ++ add_shares}

理解

%{map | shares: (for share <- add_shares, into: map[:shares], do: share)}

Enum.reduce

Enum.reduce(add_shares, map, fn share, acc ->
  %{acc | shares: [share | acc[:shares]]}
end)

Enum.into

%{map | shares: Enum.into(add_shares, map[:shares], & &1)}

<强> FWIW:

将元素添加到现有列表中:

list = []
element = 42

list1 = [element | list]
#⇒ [42]
list2 = [element | list1]
#⇒ [42, 42]

回答更新的问题(简化):

Enum.reduce(email_array, {[], []}, fn
  email, {shares, changes} = _acc ->
    with {:found_user, sharee} <- ensure_user(email) do
      case :camera_share do
        {:ok, camera_share} ->
           {[camera_share | shares], changes}
        {:error, changeset} ->
           {shares, [changeset | changes]}
      end
    else
      # basically the same
      # make sure ALL branches return an acumulator
    end
  end)

以上内容会返回您可能分配给任何内容的元组{shares, changes}

答案 1 :(得分:0)

您可以创建一个这样的简单方法:

/usr/bin/python

并调用它将项目添加到地图中的列表中:

def add_share(%{shares: shares} = map, share) do
  %{ map | shares: [share | shares] }
end

结果:

%{shares: []}
|> add_share(%Cs{name: "Junaid1"})
|> add_share(%Cs{name: "Junaid2"})