F#: The use keyword and using function
While I was playing around with the little F# script that I wrote to try and solve the word count problem I noticed that in a couple of places I had used the 'use' keyword when dealing with resources that needed to be released when they’d been used.
Using the 'use' keyword means that the 'Dispose' method will be called on the resource when it goes out of scope.
The two examples were 'StreamWriter' and 'StreamReader':
let writeTo (path:string) f =
use writer = new StreamWriter(path)
f writer
let download path =
use streamReader = new StreamReader(File.OpenRead path)
streamReader.ReadToEnd()
I found it quite annoying that those bits of code needed to take up three lines despite the fact I don’t really need to have the class construction assigned.
Luckily there is a 'using' function available which allows us to make these bits of code more concise.
'using' takes in 2 arguments - the object to be created and a function which takes in that object and does something with it.
If we make use of that function instead of the 'use' keyword we end up with the following function definitions:
let writeTo (path:string) f = using (new StreamWriter(path)) (fun writer -> f writer)
let download path = using (new StreamReader(File.OpenRead path)) (fun reader -> reader.ReadToEnd())
When we’re just doing one thing with the resource, as I am here, then I think this reads better. If we’re using it for multiple different operations then perhaps the use keyword is more appropriate.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.