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))
- run
elixir left_triangle.ex
Result
*
**
***
****
*****
******
*******
********
*********
**********
***********
*
**
***
****
*****
******
Happy Coding!
Top comments (1)
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 optimizedAlso, 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).