Elixir Today: Creating a Square Pattern using Elixir

Process

  • create an elixir file named square.ex
  • write the code
square = fn n ->
  string =
    for x when x < n <- 0..n do
      for y when y < n <- 0..n do
        " *"
      end
    end

  result =
    Enum.into(string, "", fn f ->
      new_string = Enum.join(f)
      "#{new_string}\n"
    end)

  result
end

IO.puts(square.(10))
IO.puts(square.(5))
  • run elixir square.ex

Result

 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *
 * * * * * * * * * *

 * * * * *
 * * * * *
 * * * * *
 * * * * *
 * * * * *

Update

square = fn n ->
  string =
    for _x <- 0..n do
      for _y <- 0..n do
        " *"
      end
    end

  result =
    Enum.into(string, "", fn f ->
      new_string = Enum.join(f)
      "#{new_string}\n"
    end)

  result
end

Update

square = fn n ->
  for _x <- 0..n do
    for _y <- 0..n do
      " *"
    end
  end
  |> Enum.into("", fn string ->
    string = Enum.join(string)
    "#{string}\n"
  end)
end

IO.puts(square.(10))
IO.puts(square.(5))

Happy Coding!

ย