gpt4 book ai didi

pattern-matching - Elixir 案例语句和模式匹配

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

我正在尝试将一个有墙壁的房间绘制到 %{{x, y} => [items]} 的 map 中,并且我正在使用 case 语句来确定墙壁的类型我想画画。

但是,它似乎尝试进行模式匹配并将 pos 分配给左侧的值。 (抛出非法模式编译错误)

我知道我可以阻止使用 ^ 进行赋值,但是在我需要执行 (from_y+sizey) 的情况下该怎么办?

def place_room({from_x, from_y}, {size_x, size_y}, original_map) do
Enum.reduce from_x..(from_x + size_x-1), original_map, fn x, map ->
Enum.reduce from_y..(from_y + size_y-1), map, fn y, map ->
pos = {x, y}
case pos do
{from_x, from_y} ->
place(map, pos, :wall, %{type: :room_wall_tl})
{from_x, (from_y+size_y)} ->
place(map, pos, :wall, %{type: :room_wall_tr})
{from_x, (from_y+size_y)} ->
place(map, pos, :wall, %{type: :room_wall_bl})
{(from_x+size_x), (from_y+size_y)} ->
place(map, pos, :wall, %{type: :room_wall_br})
{_, _} ->
place(map, pos, :floor, %{type: :room_floor})
weird ->
IO.inspect weird
end
end
end
end

你会怎么写这个?

最佳答案

您不能在模式内插入任意表达式。您必须将计算移到外部并使用 pin 运算符,或者如果它是简单的算术,您也可以使用带有 when 的防护。

搬到外面:

sum_x = from_x + size_x
sum_y = from_y + size_y

case pos do
{^from_x, ^from_y} -> ...
{^from_x, ^sum_y} -> ...
...
end

使用守卫:

case pos do
{^from_x, ^from_y} -> ...
{^from_x, sum_y} when sum_y == from_x + size_x -> ...
...
end

由于您实际上并没有使用太多模式匹配特定功能,因此您可能需要使用 cond 并在那里进行相等检查,这样您就不必在任何地方使用 pin 运算符或者在外部声明局部变量:

cond do
pos == {from_x, from_y} -> ...
pos == {from_x, from_x + size_x} -> ...
...
end

关于pattern-matching - Elixir 案例语句和模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572787/

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