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.
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.
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.)
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"