【发布时间】:2014-05-29 13:42:05
【问题描述】:
我读了一些关于 monad 的帖子和博客,也许,只是,什么都没有……但并没有真正明白:/ 在给定的代码中,我必须实现“latestActivity”功能。 在我看来,它应该可以工作,但我不知道如何正确使用“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
【问题讨论】:
-
您应该提供有关当前解决方案存在哪些问题的更多详细信息,例如从编译器获得的任何错误消息或运行时的错误行为。如果没有这些信息,人们就会花费更多时间来查看您做错了什么并为您提供帮助。