1

我正在尝试编写小型时间跟踪应用程序,我在其中编写我所做的事情,它只是记录它。

我成功实现了向日志添加条目,但是现在,我想更新最后一个日志条目的持续时间(例如,当我在 00:01 开始编程时,现在是 00:20,我开始在 SO 上写问题,所以当我将该日志条目添加到列表中,我希望列表头的持续时间为 19 分钟,所以我知道我花了多少时间进行编程)。

我尝试使用以下代码来做到这一点:

addEntry: Model -> List LogEntry
addEntry model =
    let
        newEntry = { -- this is what we add
            text = model.currentText,
            timestamp = model.now,
            duration = Nothing
        }
        lastEntry =
            List.head model.log
    in
       case lastEntry of
           Nothing ->
                [newEntry] -- when the list was empty - create it with one element
           Just le -> -- when not empty
                newEntry :: {le | duration = newEntry.timestamp - le.timestamp } :: List.tail model.log
 -- - add new element, modified head and tail

问题是List.tail model.logMaybe List LogEntry我希望它是Just List LogEntry。它只能在Just List LogEntry那里,因为 head 也是Just LogEntry

在那里做什么?嵌套另一个case并将一个分支标记为不可访问?有一些模式如何做到这一点?或类似的函数List a -> Maybe (a, List a),返回头和尾相同Maybe

4

1 回答 1

3

在列表上使用模式匹配(列表可能是空列表或头部和尾部的缺点):

let newEntry = {
  text = model.currentText,
  timestamp = model.now,
  duration = Nothing
}
in case model.log of
  [] -> [newEntry]
  le :: log -> 
    let le' = { le | duration = newEntry.timestamp - le.timestamp }
    in newEntry :: le' :: log
于 2016-09-02T21:44:56.253 回答