(Very experienced procedural programmer trying to learn elxir, so please excuse noob questions.)
Following on from my ‘how to read file line by line’ post.
Simple need, a function that returns the next non blank line from a file. Its already open, so I need pass the io returned from open as an arg. I know I need to recurse ( I think) but none of the ‘getting started with recursion in elixir’ articles help.
Non blank means len > 0 after strip all whitespace
For these things you want to pattern match either by “\n” or ?\n
Also, before you start playing around with streams then I would recommend you to build a recursive function that walks the binary and accumulates the result to iodata.
It will teach you everything you’ll need to know and you can then apply it to streams.
its not the detection of blank line (I said what blank line means in this case in the question) I am stuck on, its the ‘looping’ . Anyway I asked gh copilot to do it for me, and I am embarrased that I couldnt work it out for myself
def next_non_blank_line(io) do
case IO.read(io, :line) do
:eof ->
:eof
line ->
if String.trim(line) == "" do
next_non_blank_line(io)
else
line
end
end
end
Yeah, you got it. Nothing to be embarrassed about, you’re learning a new language and a functional one.
Although, you can easily make the function branchless, not that you need it now, but I still recommend to take a look at the Erlang docs for building recursive functions.
i want to get into good habits, how would you improve it, also pointers to recursion docs would be great, so many of them are either, factorial or similar things that I would have written recursively before.