Hi, I am a newbie to Elixir so please forgive this basic question. I have written a stream function using Stream.unfold that produce a potentially infinite series of numbers. I would like to output these to a text file for offline analysis but I’m having trouble locating the appropriate idiom. This is usually trivial in most other languages but I want to do it in a way that conforms to the ‘functional’ outlook, including appropriate use of the pipe operator.
The values are all being concatenated together in the output file, while I would like them to be on separate lines. I think I could use a map function to transform the text, but this feels really clunky.
The introduction of the output file in the middle of the sequence feels a bit procedural, where I am trying to become more functional.
As it stands, the code doesn’t protect from file open errors, which doesn’t feel right.
You’re always free to move the output stream creation external to some other function IE
def stream_file(input, output) do
input
|> Stream.take(10)
|> Stream.into(output)
end
Now you can create the whole stream via a completely pure function. Your side effects would then get pushed to wherever you want to call that function from IE:
This is more along the lines of erlang’s “let it crash” philosophy. What you have here is fine. In many cases if the files don’t exist, there’s no right thing to do, just crash cause it won’t succeed anyway. If you have some other thing you want to do you can wrap it in a try block, or if it’s in another process you can monitor that process and handle its failure accordingly.
One other point, you generally don’t need to specify the :write or :utf8 flags. Stream.into will handle setting the write flag, and utf8 is also often not necessary if you’re streaming in bytes.