将Erlang(或Elixir)中的元组与记录进行匹配的模式是不好的做法?与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
所以用“标签”字段霸菱一个“家”的价值每记录将第一条相匹配。当然,那里会有一些表现处罚。
另外一个原因是,你可能要在这种情况下,直接以更改记录定义(例如添加新字段)模式匹配将需要修改,而Parroty解决方案仍然很好。恕我直言,这是使用记录而不是元组的原因,所以这就是为什么不使用与记录直接模式匹配很重要的原因。 – Pascal
实际上它们过于谨慎了,记录被**定义为元组,其中第一个元素是记录名,然后按照与记录定义中相同的顺序跟随记录字段。然而,混合记录语法和元组语法被认为是糟糕的风格,因为它消除了使用记录的一个主要优点。 – rvirding