Embed Directive in PureScript
Here’s the translation of the Go code to PureScript, along with explanations in Markdown format suitable for Hugo:
PureScript doesn’t have a direct equivalent to the embed
directive, but we can simulate similar functionality using the Node.ReadFile
module. Note that this approach will work for server-side PureScript applications, but not for browser-based ones.
First, let’s start with the basic structure and imports:
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.Encoding (Encoding(..))
import Node.FS.Sync (readTextFile)
import Data.Either (Either(..))
Now, let’s define our main function:
main :: Effect Unit
main = do
-- Read the contents of 'single_file.txt'
fileContent <- readTextFile UTF8 "folder/single_file.txt"
log fileContent
-- Read multiple files
content1 <- readTextFile UTF8 "folder/file1.hash"
log content1
content2 <- readTextFile UTF8 "folder/file2.hash"
log content2
In PureScript, we use the readTextFile
function from the Node.FS.Sync
module to read file contents. This function returns an Effect
that, when run, will read the file and return its contents as a String
.
To run this example, you would need to create the necessary files and folders:
$ mkdir -p folder
$ echo "hello purescript" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash
Then, compile and run the PureScript code:
$ spago build
$ spago run
hello purescript
123
456
Note that PureScript doesn’t have a direct equivalent to Go’s embed
directive. In PureScript, file reading is typically done at runtime rather than compile-time. If you need to embed files at compile-time in a PureScript project, you might need to use a build tool or custom preprocessor to achieve similar functionality.
Also, PureScript’s type system and pure functional nature mean that file I/O operations are explicitly marked as effects, which is why we use the Effect
monad in our main
function.