Haskell - 如何将字符串转换为整数并将其传递给创建的结构?

时间:2016-04-12 17:10:06

标签: haskell

我正在实施CIS 194课程并找到一项我无法解决的任务。

我有一个LogMessage数据:

type TimeStamp = Int
data LogMessage = LogMessage MessageType TimeStamp String
                | Unknown String
  deriving (Show, Eq)

我想通过向其发送数组(如LogMessage)来创建["I", "215" "somesomesome"]

createLogMessage :: [String] -> LogMessage
createLogMessage ("I":timestamp:message) = LogMessage Info timestamp message

问题是时间戳应该转换为整数。如何将时间戳转换为整数并将其传递给LogMessage

1 个答案:

答案 0 :(得分:4)

Read类仅为此类转换提供函数read :: Read a => String -> a。 (另外,您还需要从列表中解压缩message,以便LogMessage获得String,而不是[String]作为其第三个参数。)

createLogMessage :: [String] -> LogMessage
createLogMessage ("I":timestamp:message:[]) = LogMessage Info (read timestamp) message

或更简单

createLogMessage ["I", timestamp, message] = LogMessage Info (read timestamp) message

Int类是Read的一个实例,Haskell可以推断read需要在此处返回Int

请注意,如果您的MessageTypeRead的实例,则可以简化createLogMessage

instance Read MessageType where
    read "I" = Info
    read "D" = Debug
    -- etc

createLogMessage :: [String] -> LogMessage
createLogMessage [msgType, timestamp, message] = LogMessage (read msgType) (read timestamp) message