DEV Community

Pau Riosa
Pau Riosa

Posted on • Updated on • Originally published at paugramming.com

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))

Enter fullscreen mode Exit fullscreen mode
  • run elixir square.ex

Result

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

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Happy Coding!

Top comments (0)