DEV Community

Pau Riosa
Pau Riosa

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

4 2

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay