gpt4 book ai didi

functional-programming - 如何在 Elm 0.17/0.18 中获取当前时间?

转载 作者:行者123 更新时间:2023-12-03 21:16:45 24 4
gpt4 key购买 nike

我已经问过这个问题了:
How do I get the current time in Elm?

并通过编写我自己的( 现在已弃用 )start-app 变体来回答它:
http://package.elm-lang.org/packages/z5h/time-app/1.0.1

当然 Elm 架构已经改变了,我以前的做事方式不再有效,因为没有信号或 Time.timestamp .

所以....

假设我使用标准更新函数签名构建一个应用程序:update : Msg -> Model -> (Model, Cmd Msg)
我想用更新时间为我的模型加上时间戳。一 Not Acceptable 几乎解决方案是订阅Time.every .从概念上讲,这不是我想要的。这是随着时间更新模型,也用消息单独更新模型。

我想要的是能够编写带有签名的更新函数:updateWithTime : Msg -> Time -> Model -> (Model, Cmd Msg)
我开始尝试通过添加一些额外的消息来解决这个问题:Msg = ... When | NewTime Time
并创建一个新命令:timeCmd = perform (\x -> NewTime 0.0) NewTime Time.now
因此,在任何操作中,我都可以发出一个额外的命令来检索时间。但这很快就会变得困惑和失控。

关于如何清理它的任何想法?

最佳答案

无需在每个更新路径上进行时间获取的一种选择是包装您的 Msg在另一种消息类型中,它将获取时间然后调用您的正常 update随着时间。这是http://elm-lang.org/examples/buttons的修改版这将在每次更新时更新模型上的时间戳。

import Html exposing (div, button, text)
import Html.App exposing (program)
import Html.Events exposing (onClick)
import Task
import Time exposing (Time)


main =
program { init = (Model 0 0, Cmd.none), view = view, update = update, subscriptions = (\_ -> Sub.none) }

type alias Model =
{ count: Int
, updateTime : Time
}

view model =
Html.App.map GetTimeAndThen (modelView model)

type Msg
= GetTimeAndThen ModelMsg
| GotTime ModelMsg Time

update msg model =
case msg of
GetTimeAndThen wrappedMsg ->
(model, Task.perform (\_ -> Debug.crash "") (GotTime wrappedMsg) Time.now)

GotTime wrappedMsg time ->
let
(newModel, cmd) = modelUpdate wrappedMsg time model
in
(newModel, Cmd.map GetTimeAndThen cmd)

type ModelMsg = Increment | Decrement

modelUpdate msg time model =
case msg of
Increment ->
({model | count = model.count + 1, updateTime = time}, Cmd.none)

Decrement ->
({model | count = model.count - 1, updateTime = time}, Cmd.none)

modelView model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (toString model.count) ]
, button [ onClick Increment ] [ text "+" ]
, div [] [ text (toString model.updateTime) ]
]

关于functional-programming - 如何在 Elm 0.17/0.18 中获取当前时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com