[Haskell-beginners] IO String inside a CmdArgs data

Daniel Fischer daniel.is.fischer at googlemail.com
Fri Jan 14 19:41:07 CET 2011


On Friday 14 January 2011 19:18:58, Kamil Stachowski wrote:
> Hello,
>
> I am trying to use N. Mitchell's CmdArgs and I would like one of the
> fields to store the current time. A minimal example below:
>
>
> {-# LANGUAGE DeriveDataTypeable #-}
>
> import System.Console.CmdArgs
> import System.Time
>
>
> data FuzzyTimeConf = FuzzyTimeConf { time :: String } deriving (Show,
> Data, Typeable)
>
> ftConf = FuzzyTimeConf { time = confDefaultTime }
>
> confDefaultTime = "it is here that I would like to get the current time"
>
> main :: IO ()
> main = do
>  print =<< cmdArgs ftConf
>
>
> I want confDefaultTime to store the current time as HH:MM, so I guess I
> will also need to extract it in some way.
>
> I've tried many different versions and can't come up with anything
> working. confDefaultTime can't be an IO String because than it can't
> derive Show and Data which is required for cmdArgs to work in
> FuzzyTimeConf. However, I don't seem to be able to find a way to make it
> a String and hold the actual current time.
>
> Can you help me, please?

Two things spring to mind:
a) don't use a top-level ftConf, get it inside IO in main:

getFTConf :: IO FuzzyTimeConf
getFTConf = do
  now <- getClockTime -- or whichever time you need
  return $ FuzzyTimeConf { time = convert now }

main = do
  ftConf <- getFTConf
  print =<< cmdArgs ftConf

b) if you absolutely have to have ftConf as a top-level name and it is safe 
here:

import System.IO.Unsafe (unsafePerformIO)

{-# NOINLINE ftConf #-}
ftConf :: FuzzyTimeConf
ftConf = unsafePerformIO $ do
  now <- getClockTime
  return $ FuzzyTimeConf { time = convert now }

a) is preferable if it's possible to do thus.

Cheers,
Daniel



More information about the Beginners mailing list