gpt4 book ai didi

erlang - 在 Erlang (Elixir) 中对作为元组的记录进行模式匹配

转载 作者:行者123 更新时间:2023-12-01 04:49:05 25 4
gpt4 key购买 nike

在 Erlang(或 Elixir)中将记录作为元组进行模式匹配是一种不好的做法吗?

示例代码:假设我们已经定义了这个模块:

defmodule Ween do
defrecord TimeSpot, at: nil, tag: nil

def proper?({ _, _, "home"} = v), do: { true, "succeeded with: #{inspect v}" }
def proper?(other), do: { false, "failed with: #{inspect other}" }

def sample, do: TimeSpot.new(tag: "home")
end

如果我们定义一个测试如下:

defmodule WeenTest do
use ExUnit.Case
require Ween

test "records are tuples" do
case Ween.proper?(Ween.sample) do
{ true, v } -> IO.puts v
assert(true)
{ false, v } -> IO.puts v
assert(false)
end
end
end

会成功的。

编辑 1:@parroty这里对测试的元组进行模式匹配的原因是为了模拟某种“某种”鸭子类型的记录;我希望的最终结果应该是这样的:

defmodule Ween do
defrecord TimeSpot, at: nil, tag: nil

def proper?([tag: "home"] = v), do: { true, "succeeded with: #{inspect v}" }
def proper?([tag: "1234"] = v), do: { true, "succeeded with: #{inspect v}" }
def proper?(other), do: { false, "failed with: #{inspect other}" }

def sample, do: TimeSpot.new(tag: "home")
end

因此,带有“标签”字段且带有“home”值的每条记录都将匹配第一个子句。当然,那里似乎会有一些性能损失。

最佳答案

Cesarini 和 Thompson 在他们的书Erlang Programming 中说,永远不要依赖记录作为元组实现的事实,因为这种实现可能会发生变化。查看接受的答案 this question .

关于erlang - 在 Erlang (Elixir) 中对作为元组的记录进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20732837/

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