Defer in PureScript
Our example demonstrates the concept of cleanup actions in PureScript. While PureScript doesn’t have a direct equivalent to Go’s defer
, we can achieve similar functionality using the Effect
monad and the bracket
function from the Control.Monad.Error.Class
module.
In this PureScript example, we’re using the bracket
function to ensure that our file is properly closed after we’re done with it, regardless of whether an error occurs during the writing process.
The bracket
function takes three arguments:
- An action to acquire a resource (in our case, opening a file)
- An action to release the resource (closing the file)
- An action to use the resource (writing to the file)
This pattern ensures that the cleanup action (closing the file) is always performed, similar to how defer
works in other languages.
We’re using the Node.FS.Sync
module for file operations, which provides synchronous file system functions. In a real-world application, you might prefer to use asynchronous versions of these functions.
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
This example demonstrates how to handle resource management and cleanup in PureScript, providing a similar functionality to the defer
keyword in other languages.