2017-02-02 91 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

很好的解釋!非常感謝。 –