如何在Elixir中循环创建地图 [英] How to create a map in a loop in Elixir

查看:68
本文介绍了如何在Elixir中循环创建地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建2d地图,并希望先用空值预先填充它。

I am creating a 2d map and want to start by pre-filling it with empty values.

我知道以下内容在Elixir中不起作用,但这是

I know the following will not work in Elixir, but this is what I am trying to do.

def empty_map(size_x, size_y) do
  map = %{}

  for x <- 1..size_x do
    for y <- 1..size_y do
      map = Map.put(map, {x, y}, " ")
    end
  end
end

然后我将画图像这样

def create_room(map, {from_x, from_y}, {width, height}) do
  for x in from_x..(from_x + width) do
    for y in from_x..(from_x + width) do
      if # first line, or last line, or first col, or last col
        map = Map.replace(map, x, y, '#')
      else
        map = Map.replace(map, x, y, '.')
      end
    end
  end
end

2D数组,但我认为平面图的坐标为t

I have tried doing it as a 2D array, but I think flat map with coordinate touples as keys will be easier to work with.

我知道我应该使用递归,但是我真的不知道如何优雅地使用它并且这种情况不断出现,我还没有看到一种简单/通用的方法来实现。

I know I am supposed to use recursions, but I don't really have a good idea of how to do it elegantly and this scenario keeps coming up and I haven't seen a simple/universal way to do this.

推荐答案

您可以使用两个在此处嵌套 Enum.reduce / 3 ,将地图作为累加器传递,而不是自己编写递归函数:

You can use two nested Enum.reduce/3 here, passing the map as the accumulator, instead of writing recursive functions yourself:

defmodule A do
  def empty_map(size_x, size_y) do
    Enum.reduce(1..size_x, %{}, fn x, acc ->
      Enum.reduce(1..size_y, acc, fn y, acc ->
        Map.put(acc, {x, y}, " ")
      end)
    end)
  end
end

IO.inspect A.empty_map(3, 4)

输出:

%{{1, 1} => " ", {1, 2} => " ", {1, 3} => " ", {1, 4} => " ", {2, 1} => " ",
  {2, 2} => " ", {2, 3} => " ", {2, 4} => " ", {3, 1} => " ", {3, 2} => " ",
  {3, 3} => " ", {3, 4} => " "}

这篇关于如何在Elixir中循环创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆