Home > front end >  How do I push a string into IO input being called from another function in Haskell?
How do I push a string into IO input being called from another function in Haskell?

Time:04-14

I have a function, that woks similar to (or), that takes in a Bool and returns True if the user input is true or the Bool is True.

I can not change anything about orFunc. It must stay the way it is

orFunc :: Bool -> IO Bool
orFunc xs = do ys <- getLine
               let rev1 = xs || (read ys::Bool)
               return rev1

so.. (orFunc False) with a user input of True would return True.

Now let's say, I want to test this function, with a series of automated inputs.

The function tester, calls our orFunc, and wants to push the word "False", conveniently located in our false.txt file, into orFunc. This way, I don't need to type the word "False" into the function every single time. It will automatically grab it from the false.txt. How do I go about doing this when orFunc doesn't take input as a parameter?

Here an example of what it should look like. This doesn't work but it's something I tried.

tester :: IO Bool -> IO Bool
tester xs = do ys <- readFile "false.txt"
               xs <- ys
               return xs

Here's how I would run some test's on it.

{--This will return True because True || False = True --}
tester (orFunc True)

{--This will return False because False || False = False --}
tester (orFunc False) 

CodePudding user response:

My best advice is Don't. Instead, abstract orFunc into a part that does IO and a part that does your business logic, and test the business logic independently of the IO.

But if you are absolutely set, one way to do this would be to open your file and duplicate its file descriptor to stdin's. Like this:

import System.IO
import System.Posix.IO

main = do
    fd <- openFile "false.txt" ReadMode >>= handleToFd
    dupTo fd stdInput
    orFunc False

This only works on Linux-alikes. It's possible Windows has a similar API somewhere, but I'm not familiar enough with it to give good pointers about where.

  • Related