标签: elixir

Elixir:在列表映射中找到最小长度列表的键

在 Elixir 的列表映射中查找与最小长度列表关联的键的有效方法是什么。假设我有:

z = %{a: [1, 2, 3], b: [4, 5], c: [6, 7, 8, 9]}
Run Code Online (Sandbox Code Playgroud)

我知道我能做到:

Enum.map z, fn {k, v} -> length(v) end
Run Code Online (Sandbox Code Playgroud)

这会给我:

[3, 2, 4]
Run Code Online (Sandbox Code Playgroud)

但我真正需要的只是答案,即与最小值 2 相关的键,当然是:b。

我将大约每秒在列表的动态映射上运行它,所以我希望它尽可能高效。

elixir

1
推荐指数
1
解决办法
1116
查看次数

Map.fetch(key, value) 和 Map.fetch!(key, value) 有什么区别

https://hexdocs.pm/elixir/Map.html#fetch/2和https://hexdocs.pm/elixir/Map.html#fetch!/2略有不同,但没有讨论有何不同。

该文档确实提到第一个是“由编译器内联”,而后者是引发异常。

我是否应该有一个经验法则来确定何时使用其中一种而不是另一种,反之亦然?

问候

elixir

1
推荐指数
1
解决办法
2301
查看次数

Ecto 在关联上运行

我运行这样的查询:

query = from q in MY.Model, preload: [:accoc], where: q.accoc_field in [10, 11]
Repo.all(query)
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

** (Ecto.QueryError) iex:32: field `accoc_field` in `where` does not exist in schema MY.Model in query:
Run Code Online (Sandbox Code Playgroud)

所以,基本上我正在尝试编写一个查询,例如:

select * from my_model m join assoc a on m.assoc_id = a.id where a.assoc_field in (10, 11)
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用 Ecto 中的联接来编写上述查询,但是在使用预加载时如何做到这一点?

elixir phoenix-framework

1
推荐指数
1
解决办法
338
查看次数

Repo.all 失败,因为我有自定义主键

我为没有字段的表生成并运行了迁移id(使用该字段league_id作为主键)。我确认迁移按预期进行(检查了 psql 中的数据库,该表确实没有id字段并且league_id是主键)。

当我运行时,Repo.all(League)出现以下错误:

13:01:14.962 [debug] QUERY ERROR source="leagues" db=2.8ms

SELECT l0."id", l0."league_id" FROM "leagues" AS l0 []

** (Postgrex.Error) ERROR 42703 (undefined_column): column l0.id does not exist

有没有办法告诉Repo.all/1没有 id 字段(除了手动构建SELECT *-type 查询之外?)

elixir ecto

1
推荐指数
1
解决办法
1417
查看次数

阻止 ecto 抛出唯一约束错误

我不断收到此错误。该错误是预料之中的,但我该如何处理这种情况,以便它不会在控制台中抛出红色文本?

代码:

  def insert_user_product(conn, user_product) do
    changeset = Api.UserProduct.changeset(%Api.UserProduct{}, user_product)
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, user_product} ->
        {:ok, user_product}
      {:error, changeset} ->
        {:error, :failure}
    end
  end
Run Code Online (Sandbox Code Playgroud)

错误:

14:23:18.273 [error] #PID<0.354.0> running Api.Router terminated
Server: 172.20.10.6:4000 (http)
Request: PUT /product/isvegan/?p_id=1&u_id=792200324272726
** (exit) an exception was raised:
    ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * unique: unique_user_product

If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and …
Run Code Online (Sandbox Code Playgroud)

elixir ecto

1
推荐指数
1
解决办法
1555
查看次数

如何平衡 Elixir 中的最大堆树?

我已经实现了最大堆树,但是当创建新节点时,树变得不平衡。例如,如果插入的大部分值都小于根值,则它成为左重树。这是因为 if-else 比较,但是还有其他方法来平衡树吗?提前致谢。

defmodule MaxHeap do

  defstruct value: nil, right: nil, left: nil

  def new(value), do: %MaxHeap{value: value}

  def insert(newValue=%MaxHeap{value: rootValue}, nextValue) do
    if nextValue <= rootValue do
      %MaxHeap{newValue | left: insert(newValue.left, nextValue)}
    else
      temp=rootValue #save old rootValue in temp, before editing it
      rootValue=nextValue
      nextValue=temp
      %MaxHeap{newValue | right: insert(newValue.right, nextValue), value: rootValue}
    end
  end

  def insert(nil, value) do
    %MaxHeap{value: value}
  end
end
Run Code Online (Sandbox Code Playgroud)

Elixir iex 中的输出树:

heap tree functional-programming elixir

1
推荐指数
1
解决办法
452
查看次数

Elixir - 将两个具有相似键名称和值的映射合并为列表?

我有两张地图:

a = %{ list: [1,2,3]}
b = %{ list: [4,5,6]}
Run Code Online (Sandbox Code Playgroud)

我希望合并/连接两个嵌套列表,结果是:

c = %{ list: [1,2,3,4,5,6]}
Run Code Online (Sandbox Code Playgroud)

我尝试过研究深度合并,但就我而言,我有列表而不是嵌套映射。

maps nested list concatenation elixir

1
推荐指数
1
解决办法
1771
查看次数

ecto 中的复合主键

在迁移中,我们可以添加多个主键,它们都充当复合主键。我的表中有四个字段,其中三个是主键并且工作正常。当我尝试添加新的迁移并将第四列设为主键时。Postgres 给了我这个错误。

\n\n
   (Postgrex.Error) ERROR 42P16 (invalid_table_definition) multiple primary keys for table "rooms_units" are not allowed\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的新迁移:

\n\n
alter table(:rooms_units) do\n  modify(:date_to, :utc_datetime, primary_key: true)  \nend \n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我将其添加到原始迁移中,则效果很好。

\n\n

这是我原来的迁移:

\n\n
  create table(:rooms_units, primary_key: false) do\n   add(:room_id, references(:rooms), null: false, primary_key: true)\n   add(:unit_id, references(:units), null: false, primary_key: true)\n   add(:date_from, :utc_datetime, null: false, primary_key: true)\n   add(:date_to, :utc_datetime, null: false, default: fragment("\'infinity\'::timestamp"))\n  end\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我在 date_to 列中添加 Primary_key: true ,则效果很好。迁移成功运行。

\n\n

所以我想语法是正确的。但它不会在新的迁移中\xe2\x80\x99 工作。

\n\n

有什么建议或解决方法吗?\n谢谢。

\n

elixir ecto

1
推荐指数
1
解决办法
3488
查看次数

使用 start_link 启动时 GenServer 不会 trap_exit

我发现当尝试捕获退出信号时,使用pid 启动 GenServer 的结果与GenServer.start运行.Process.linkGenServer.start_link

这是我用来演示该问题的实验代码:

defmodule Foo do
  defmodule Server do
    def init(_) do
      Process.flag(:trap_exit, true)
      {:ok, nil}
    end
    def handle_info({:EXIT, from, reason}, _) do
      IO.inspect({:kill_signal, from, reason})
      {:noreply, nil}
    end
  end

  def foo() do
    Process.flag(:trap_exit, true)
    # version 1
    {:ok, pid} = GenServer.start_link(Server, nil)

    # version 2
    # {:ok, pid} = GenServer.start(Server, nil)
    # Process.link(pid)

    # print process info
    IO.inspect({self(), pid, Process.info(pid)})

    Process.exit(pid, :reason)

    :timer.sleep(200)
  end
end

Foo.foo
Run Code Online (Sandbox Code Playgroud)

在版本 1 中,EXIT 信号导致Server退出而不会被捕获在其handle_info …

erlang elixir erlang-otp gen-server

1
推荐指数
1
解决办法
981
查看次数

循环 ExUnit 测试时,Enum.each 丢失变量

运行以下代码时,我收到警告:

warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name
  test/my_module_test.exs:7
Run Code Online (Sandbox Code Playgroud)

接下来是失败的测试:

== Compilation error in file test/my_module_test.exs ==
** (CompileError) test/my_module_test.exs:7: undefined function char/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:767: Code.require_file/2
    (elixir) lib/kernel/parallel_compiler.ex:209: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6
Run Code Online (Sandbox Code Playgroud)
warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name
  test/my_module_test.exs:7 …
Run Code Online (Sandbox Code Playgroud)

elixir ex-unit

1
推荐指数
1
解决办法
740
查看次数