Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read a file specified as a parameter to a function when running GHCI

Tags:

haskell

ghci

I'm using ghci 6.10.4 at the dos command line in XP, and also in emacs using haskell-mode-2.4

When running programs that operate on stdin, is there a way I can redirect a file to be stdin? For example if I have a function called main that reads from stdin, I can't do:

*Main> main < words.txt

Is there another way?

Also I would like to be able to type stdin into the ghci window, which seems to work, but what is the EOF key? I thought it was Ctrl-D but that doesn't work.

like image 383
justinhj Avatar asked Nov 14 '09 19:11

justinhj


People also ask

How to load a file in GHCi?

GHCi is the interactive interface to GHC. From the command line, enter "ghci" (or "ghci -W") followed by an optional filename to load. Note: We recommend using "ghci -W", which tells GHC to output useful warning messages in more situations. These warnings help to avoid common programming errors.

How do I run a program in GHCi?

Open a command window and navigate to the directory where you want to keep your Haskell source files. Run Haskell by typing ghci or ghci MyFile. hs. (The "i" in "GHCi" stands for "interactive", as opposed to compiling and producing an executable file.)

What does GHCi mean in Haskell?

GHCi [1] is GHC's interactive environment that includes an interactive debugger (see The GHCi Debugger). GHCi can. interactively evaluate Haskell expressions. interpret Haskell programs. load GHC-compiled modules.


2 Answers

This will be easier if you rework your main to open the file itself.

import System.Environment
import System.IO

main :: IO ()
main = do
    args <- getArgs
    case args of
      [] -> doStuff stdin
      file:_ ->
        withFile file ReadMode doStuff

doStuff :: Handle -> IO ()
doStuff = …
*Main> System.Environment.withArgs ["main.txt"] main

Don't give a EOF on stdin while within GHCi. If you do, all further attempts to read from stdin will fail:

Prelude> getLine
*** Exception: <stdin>: hGetLine: illegal operation (handle is closed)
Prelude> getContents
*** Exception: <stdin>: hGetContents: illegal operation (handle is closed)
like image 185
ephemient Avatar answered Oct 05 '22 00:10

ephemient


You CAN type :main in GHCi to invoke command line parameters. I'm afraid you'll probably just want to use that.

like image 41
codebliss Avatar answered Oct 04 '22 23:10

codebliss