DEV Community

Pau Riosa
Pau Riosa

Posted on • Originally published at paugramming.com

4 3

Elixir Today: Create a Left Triangle Pattern using Elixir

Process

  • create a file named left_triangle.ex
  • write the code
left_triangle = fn n ->
  for i <- 0..n do
    for _ <- 0..i do
      "*"
    end
  end
  |> Enum.into("", fn string ->
    string = Enum.join(string)
    "#{string}\n"
  end)
end

IO.puts(left_triangle.(10))
IO.puts(left_triangle.(5))
Enter fullscreen mode Exit fullscreen mode
  • run elixir left_triangle.ex

Result

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

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

Enter fullscreen mode Exit fullscreen mode

Happy Coding!

Top comments (1)

Collapse
 
pyrsmk profile image
Aurélien Delogu

This code needs some optimization because you have a nested loop. Can't you directly output the number of * you need with a simple Elixir function? Internally it would still be a loop, but more optimized

Also, can't you pass an IO to your function so it's responsible of displaying things the right way? I mean, if you pass an IO, you can drop your last Enum loop and you avoid putting strings on the heap which is really inefficient (I don't know if it works like that in Elixir but it's the case in Rust, Crystal, and many other languages).

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

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

Okay