Handle from String

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.

1 Like

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.

1 Like

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.

1 Like

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 :slight_smile:

Does this help?

4 Likes

Yup, I also suggested that an How to implement a transcript program in Haskell? - #2 by tomjaguarpaw