Stream: beginners

Topic: Releasing resources in case of error


view this post on Zulip Aurélien Geron (Sep 12 2024 at 05:39):

Newbie question: how does Roc handle releasing resources in case of error?

I want to write a script that opens a huge file foo.txt, read it line per line, do something to each line (e.g., add the line number), and output the result (also line per line) into bar.txt. I need file handles for a while, and I want to make sure they are properly closed when I'm done.

Is it possible to open a file for writing and keep the handle for a while using the basic-cli? I've looked at the File docs, but I can't see close or Writer, so I'm not sure it's possible yet, unless I've missed something.

Assuming it exists (now or in the future), what if something fails in the middle of the job and I need to exit from the function: I'd like to ensure that the files are closed properly. Is it fully my responsibility or does Roc or the platform take care of this automatically (e.g., via ref counting and destructors)? It would be nice if I could just use the ? or ! operator and exit without having to worry about releasing resources, but perhaps that's impossible.

view this post on Zulip Brendan Hansknecht (Sep 12 2024 at 13:40):

It is up to the platform to decide that

view this post on Zulip Brendan Hansknecht (Sep 12 2024 at 13:41):

For basic-cli, it should just close when there are no reference to a file in roc anymore

view this post on Zulip Aurélien Geron (Sep 12 2024 at 19:52):

Thanks Brendan, that's great.
It looks like there's File.openReader (with a nice example) but no File.openWriter. I might try to add that, or else I don't think my use case is possible, right?

view this post on Zulip Brendan Hansknecht (Sep 12 2024 at 19:55):

ah yeah, I guess for writing files, we only writing an entire file at once.

view this post on Zulip Brendan Hansknecht (Sep 12 2024 at 19:56):

So yeah, we need a file writer that is a mirror of file reader to do what you want


Last updated: Jul 06 2025 at 12:14 UTC