我读了一些关于 monad 的帖子和博客,也许,只是,什么都没有……但并没有真正明白:/ 在给定的代码中,我必须实现“latestActivity”-function。在我看来,它应该可以工作,但我不知道如何正确使用“Just”。也许有人能够帮助我。
module LatestActivity where
{-
Write a function 'latestActivity' that finds that last time a specific user
has sent a message. It is given a user name and a list of messages. A message
consists of the time it was sent, the user name of the user who sent it and
the message content. If there is no message from the given user in the list
the function yields 'Nothing'. Otherwise it yields 'Just' the latest time stamp
of the messages of that user in the list.
-}
import Data.List (sort)
-- | A time stamp represented as an 'Integer'
type AbsoluteTime = Integer
-- | A user name represented as a 'String'
type UserName = String
-- | A message consists of the time it was sent, the user who sent it
-- and the actual message content.
data Message = Message {
_timeStamp :: AbsoluteTime,
_userName :: UserName,
_messageContent :: String}
-- | Given a user name and a list of sent messages finds 'Just' the last time
-- a user has sent a message or 'Nothing' if the user has not sent anything.
-- The messages are not assumed to be ordered in any way.
latestActivity :: UserName -> [Message] -> Maybe AbsoluteTime
latestActivity _ [] = Nothing
latestActivity x y =
if (x == (_userName (last y))) -- x equals username in last list element?
then (_timeStamp (last y)) -- print it
else (latestActivity x init y) -- otherwise delete last listelement, recursion till list is empty