1

次のように、Web ページのタイトルを現在の年を含む文字列に設定しようとしています。

getCurrentYear :: IO String
getCurrentYear = do
    now <- getCurrentTime
    let today = utctDay now
    let (year, _, _) = toGregorian today
    return $ show year

title :: IO Html
title = do
    y <- getCurrentYear
    return $ toHtml $ "Registration " ++ y

getRootR :: Handler RepHtml
getRootR = do
    (widget, enctype) <- generateFormPost personForm -- not important for the problem at hand, comes from the example in the yesod book
    defaultLayout $ do
        setTitle title -- this is where I get the type error
[...]

これをコンパイルしようとすると、setTitle行に次のエラーが表示されます。

Couldn't match expected type `Html' with actual type `IO Html'
In the first argument of `setTitle', namely `title'
[...]

IOモナドから現在の年を取得できません(またはsetTitle関数をそれに持ち上げます)。私はさまざまなことを試しましたが成功しませんでした。つまり、これはおそらく私がまだ Haskell の型システムを理解していないという事実に帰着します ;-) 教えてもらえますか?

4

2 に答える 2

5

あなたtitleHtmlそれ自体が価値ではありません。に包まれていIOます。最初に抽出する必要があります。

getRootR = do
    [...]
    defaultLayout $ do
        unwrappedTitle <- title
        setTitle unwrappedTitle
    [...]
于 2013-05-08T08:38:13.727 に答える
2

わーい、見つけた!!!解決策は使用することliftIOです:

import Control.Monad.IO.Class (liftIO)

getRootR = do
    [...]
    defaultLayout $ do
        unwrappedTitle <- liftIO title
        setTitle unwrappedTitle
    [...]
于 2013-05-08T22:05:17.217 に答える