How to create a Handle from a String, without a real file in the file system? The contents of the handle would be the given string.
Can you explain further, what do you mean by a Handle
that does not correspond to a file in the file system? Do you mean something like stdout :: Handle
that corresponds to a standard âchannelâ rather than a file? For example:
toHandle :: String -> Either String Handle
toHandle s = case s of
"stdout" -> Right stdout
"stdin" -> Right stdin
"stderr" -> Right stderr
_otherwise -> Left $ "Error: '" <> s <> "' does not refer to a non-file Handle."
I am thinking about a handle created on memory. Its contents would be given my a string at creation time. Then another part of the program would use it for obtaining its input.
I would use it for testing programs submitted by my students. There could be many input tests, and I would write them directly in Haskell. I want to avoid saving these inputs directly in files in the file system.
I donât remember how successful I was, but I had to do something like this in the past to buffer for a TTY terminal for GHCJS because there were no real handles.
Youâll want to read the documentation on Handle. After that youâll probably need to use mkFileHandle, which means making some data type InMemoryDevice
that implements IODevice and then BufferedIO too.
Specifically, from BufferedIO:
Devices that implement
BufferedIO
include ordinary files, memory-mapped files, and bytestrings.
Emphasis mine. Note that ByteString
does not actually have a BufferedIO
instance.
Sorry, I completely misunderstood what you were originally requesting!
You can embed test data into Haskell code, but dump it into a temporary file on the fly and run studentsâ program on it. I donât see a good reason to fiddle with handles here.
What I have done is instead of passing around IO.Handle, pass around Text.IO.hGetLine hdl
aka IO Text
, or whatever is appropriate for that system. Now itâs easy to make a pure version. This is just one of those âwrite to interface not to implementationâ transformations.
Of course if itâs submitted by students and they use IO.Handle because the assignment told them to, then canât blame them for that. But you could also say âwrite to a IO Text interfaceâ and maybe they would also learn something about interface vs implementation
Does this help?
Yup, I also suggested that an How to implement a transcript program in Haskell? - #2 by tomjaguarpaw