Search code examples
haskellghci

Can't use -interactive-print to print timestamps after each line in ghci


I'm trying to print the current time after each line evaluated in ghci. Here's my code so far:

module TimePrint (timePrint) where

import System.IO
import Data.Time

getTime :: IO String
getTime = do
    now <- getCurrentTime
    return (formatTime defaultTimeLocale "%T" now)

timePrint :: Show a => a -> IO ()
timePrint a = putStrLn $ show a ++ "\n" ++ getTime

And I'm running ghci like so: ghci -interactive-print=TimePrint.timePrint TimePrint

The error I'm getting is this:

TimePrint.hs:12:44:
    Couldn't match expected type ‘[Char]’ with actual type ‘IO String’
    In the second argument of ‘(++)’, namely ‘getTime’
    In the second argument of ‘(++)’, namely ‘"\n" ++ getTime’
Failed, modules loaded: none.

I gather it has something to do with the fact that timePrint isn't in the IO monad, but other than that I have no clue. Any ideas? I'd like each line of ghci output to look something like:

Prelude> 1+2
3
11:59:20
Prelude> 3+4
7
12:00:16

etc.


Solution

  • timePrint a = do
       s <- getTime
       putStrLn $ show a ++ "\n" ++ s
    

    ++ wants a string, not an IO action.