I am new to Haskell.
I am having a really difficult time outputting command results from GHCi to a file. I was wondering if someone can give me a simple explanation on how to do this? The examples I have found online so far seem over complicated.
Quits GHCi. You can also quit by typing control-D at the prompt. Attempts to reload the current target set (see :load ) if any of the modules in the set, or any dependent module, has changed.
If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu. And you are presented with a prompt. The Haskell system now attentively awaits your input.
Introduction. GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted.
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.
Let's suppose you have a function mungeData
and you do
ghci> mungeData [1..5]
[5,2,5,2,4,6,7,4,6,78,4,7,5,3,57,7,4,67,4,6,7,4,67,4]
You can write this to file like this:
ghci> writeFile "myoutput.txt" (show (mungeData [1..5])
I'd be inclined to write
ghci> writeFile "myoutput.txt" $ show $ mungeData [1..5]
to get rid of a few brackets.
You could get that back using
ghci> fmap (read::String -> [Int]) $ readFile "myoutput.txt"
You could output it a line per number like this:
ghci> writeFile "myoutput'.txt" $ unlines.map show $ mungeData [1..5]
which reads back in as
ghci> fmap (map read.lines::String -> [Int]) $ readFile "myoutput'.txt"
This post on Reddit describes how to colorize your GHCi output (GHC >= 7.6). Instead of a prettyprinter, you could specify a logging function. For example, add the following to your .ghci.conf
:
:{
let logFile = "/home/david/.ghc/ghci.log"
maxLogLength = 1024 -- max length of a single write
logPrint x = appendFile logFile (take maxLogLength (show x) ++ "\n") >> print x
:}
:set -interactive-print=logPrint
This will log GHCi's output to ghci.log
.
The logging file must already exist, otherwise appendFile
will complain. You'll have to create that manually.
It has to fit in a let
statement, otherwise GHCi will reject it. Use :{ :}
to add multiline support in GHCi.
Apparently, using :l
gets rid of all imports you've made in your ghci.conf
, therefore you're limited to Prelude functions. The Reddit post mentions that you can somehow redefine :l
, but I don't know anythng about that. (If you know how to do this, you can of course automatically generate the logfile if it doesn't exist.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With