Édipo Féderle
Édipo Féderle

Reputation: 4257

Haskell add a UTCTime to a custom data attribute

I need a help on how I can use a do block (to perform IO) in the follow function. Bassicaly I have a Entry like:

data Entry = Entry
  { entryHeader :: String
  , entryBody :: Maybe T.Text
  , entryTags :: [String]
  , entryTime :: UTCTime
  } deriving (Generic, Show, Eq, Ord)

And the follow functions:

getNow :: IO UTCTime
getNow = do
  now <- liftIO getCurrentTime
  pure now


buildNewItem :: TuidoState -> TuidoState
buildNewItem s =
  do
    now <- getNow
    let nextID = 10 
        headerTitle = head $ BE.getEditContents $ _theEdit s
        newEntry = Entry { entryHeader = headerTitle
                         , entryBody = Just ("Test")
                         , entryTime = now <------ how use getNow here.
                         , entryTags = [headerTitle]
                       }
      actualEntries = (_entries s)
  in if headerTitle /= ""
     then s { _entries = BL.listInsert 0 newEntry actualEntries }
     else s

Of course, it does not work, I have problems understanding how I need to arrange my code to deal with pure and impure functions, and how to put it together.

Some help here? I'm accepting the suggestion of readings regarding this subject too.

Thanks in advance.

Upvotes: 0

Views: 75

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152707

Simply admit, as getCurrentTime and getNow do, that you are doing IO:

buildNewItem :: TuidoState -> IO TuidoState
...
  in pure $ if ...

Upvotes: 1

Related Questions