Haskell函数将日期的一部分作为字符串

rob*_*sha 6 io monads datetime haskell

我有一个关于日期和StringHaskell 的初学者问题.

我需要像String在Haskell中那样获得日期(年,月或日)的一部分.我发现,如果我在GHCi中写下以下两行

Prelude> now <- getCurrentTime
Prelude> let mon = formatTime defaultTimeLocale "%B" now
Run Code Online (Sandbox Code Playgroud)

mon是类型String.但是,我无法将其置于一个功能中.我试过以下内容:

getCurrMonth = do
    now <- getCurrentTime
    putStrLn (formatTime defaultTimeLocale "%B" now)
Run Code Online (Sandbox Code Playgroud)

但这会返回类型IO (),我需要String(也不是IO String,只String).

我理解该do语句创建了一个我不想要的monad,但我一直无法找到任何其他解决方案来获取Haskell中的日期.

那么,有没有办法写这样的函数?

在此先感谢您的帮助!

Don*_*art 10

如果你想返回一个字符串表示当前时间,就会要在IO单子,由于当前时间的值总是在变化!

你可以做的是在IO monad中返回一个String:

> getCurrMonth :: IO String
> getCurrMonth = do
>    now <- getCurrentTime
>    return (formatTime defaultTimeLocale "%B" now)
Run Code Online (Sandbox Code Playgroud)

然后,从你的顶层(例如在main中),你可以传递String:

> main = do
>     s <- getCurrMonth
>     ... do something with s ...
Run Code Online (Sandbox Code Playgroud)


Dan*_*ton 5

如果你真的想要那种纯函数,那么你需要明确地传递时间作为参数.

import System.Locale (defaultTimeLocale)
import System.Time (formatCalendarTime, toUTCTime, getClockTime, ClockTime)

main = do now <- getClockTime
          putStrLn $ getMonthString now

getMonthString :: ClockTime -> String
getMonthString = formatCalendarTime defaultTimeLocale "%B" . toUTCTime
Run Code Online (Sandbox Code Playgroud)

请注意,getMonthString由于IO操作getClockTime在其他地方执行,因此可以是纯粹的.

我使用了旧时功能,因为我在键盘上测试它,显然没有更新的时间包.:(我是旧时功能的新手,所以这可能会在几个小时后使用toUTCTime.

  • +1用于显示如何使"不纯部分"尽可能小. (2认同)