Elixir Today: Creating a Square Pattern using Elixir

Photo by Vincent LaVigna on Unsplash

Elixir Today: Creating a Square Pattern using Elixir

paugramming's photo
paugramming
·Apr 27, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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!

Did you find this article valuable?

Support paugramming by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this