2017-02-02 90 views
1

您好,我是Elm的全新人物,我在获取当前时间和将它转换为Elm中的日期方面遇到了一些困难。Convert Time.now to Date - Elm

我有一个消息类型 -​​ 消息和一个函数添加一个新的消息到模型。我正在尝试存储消息发布的时间以及文本和用户标识。

不过,我不断收到此错误 -

The argument to function `fromTime` is causing a mismatch. 

59|    Date.fromTime (currentTime Time.now) 
          ^^^^^^^^^^^^^^^^^^^^ 
Function `fromTime` is expecting the argument to be: 

Time 

But it is: 

x -> Time -> Time 

Hint: It looks like a function needs 2 more arguments. 

下面是代码

type alias Message = 
    { text : String, 
     date : Date, 
     userId : Int 
    } 

currentTime : task -> x -> Time -> Time 
currentTime _ _ time = 
    time 

newMessage : String -> Int -> Message 
newMessage message id = 
    { text = message 
    , date = Date.fromTime (currentTime Time.now) 
    , userId = id 
    } 

我实在想不通是怎么回事。任何帮助将非常感激。谢谢。

回答

3

Elm是一种纯粹的语言,函数调用是确定性的。请求当前时间稍微复杂一点,因为我们没有可以调用的函数,这会根据一天的时间返回给我们不同的时间。具有相同输入的函数调用将始终返回相同的内容。

获得当前时间在于副作用之地。我们必须要求建筑以纯粹的方式给我们时间。榆树处理的方式是通过TaskProgram功能。您通过update函数中的Cmd向Elm Architecture发送Task。然后Elm Architecture在幕后完成它自己的功能以获取当前时间,然后以纯代码响应另一个函数调用函数。

下面是一个简单的示例,您可以将其粘贴在http://elm-lang.org/try,您可以在其中单击按钮查看转换为Date的当前时间。

import Html exposing (..) 
import Html.Events exposing (onClick) 
import Time exposing (..) 
import Date 
import Task 

main = 
    Html.program 
     { init = { message = "Click the button to see the time" } ! [] 
     , view = view 
     , update = update 
     , subscriptions = \_ -> Sub.none 
     } 

type alias Model = { message: String } 

view model = 
    div [] 
    [ button [ onClick FetchTime ] [ text "Fetch the current time" ] 
    , div [] [ text model.message ] 
    ] 


type Msg 
    = FetchTime 
    | Now Time 


update msg model = 
    case msg of 
    FetchTime -> 
     model ! [ Task.perform Now Time.now ] 

    Now t -> 
     { model | message = "The date is now " ++ (toString (Date.fromTime t)) } ! [] 

如果你熟悉JavaScript,该Now消息的目的可以是松散看作是一个回调函数,它提供的参数是由榆树架构发送的时间。

+0

很好的解释!非常感谢。 –