Datetime Haskell函数以字符串形式获取部分日期

Datetime Haskell函数以字符串形式获取部分日期,datetime,haskell,io,monads,Datetime,Haskell,Io,Monads,我有一个关于Haskell中日期和String的初学者问题 我需要在Haskell中获取部分日期(年、月或日)作为String。我发现,如果我在GHCi中写下以下两行 Prelude> now <- getCurrentTime Prelude> let mon = formatTime defaultTimeLocale "%B" now 但是它返回类型IO(),我需要String(也不是IO String,只有String) 我知道,do语句创建了一个monad,这是我不

我有一个关于Haskell中日期和
String
的初学者问题

我需要在Haskell中获取部分日期(年、月或日)作为
String
。我发现,如果我在GHCi中写下以下两行

Prelude> now <- getCurrentTime
Prelude> let mon = formatTime defaultTimeLocale "%B" now
但是它返回类型
IO()
,我需要
String
(也不是
IO String
,只有
String

我知道,
do
语句创建了一个monad,这是我不想要的,但我一直无法在Haskell中找到任何其他获取日期的解决方案

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


提前感谢您的帮助

如果要返回表示当前时间的字符串,它必须在IO monad中,因为当前时间的值总是在变化

您可以做的是在IO monad中返回一个字符串:

> getCurrMonth :: IO String
> getCurrMonth = do
>    now <- getCurrentTime
>    return (formatTime defaultTimeLocale "%B" now)
getCurrMonth::IO字符串 >getCurrMonth=do >现在返回(formatTime defaultTimeLocale“%B”现在) 然后,您可以从顶层(例如在main中)传递字符串:

> main = do
>     s <- getCurrMonth
>     ... do something with s ...
>main=do
>s。。。用s做点什么。。。

正如唐所说,在这种情况下无法避免使用单子。请记住,Haskell是一种纯函数式语言,因此在给定特定输入的情况下,函数必须始终返回相同的输出。Haskell.org提供了一个很好的解释和介绍,当然值得一看。您还可能受益于monad简介或Haskell I/O教程等。当然,你可以在网上找到更多的资源。单子一开始可能让人望而生畏,但它们并不像一开始看起来那么难

哦,我强烈建议不要使用
unsafePerformIO
。有一个很好的理由,它的名字中有“不安全”一词,而且它肯定不是为这种情况创建的。使用它只会导致坏习惯和问题


祝你学习哈斯克尔好运

你不能只得到一个字符串,它必须是IO字符串。这是因为getCurrMonth不是一个纯函数,它在不同的时间返回不同的值,因此它必须在IO中。

如果您真的需要这种纯函数,那么您需要将时间作为参数显式传递

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
import System.Locale(defaultTimeLocale)
导入System.Time(formatCalendarTime、ToutTime、getClockTime、ClockTime)
main=do now字符串
getMonthString=formatCalendarTime defaultTimeLocale“%B”。兜售时间
请注意
getMonthString
可以是纯的,因为IO操作
getClockTime
在其他地方执行


我使用了这些函数,因为我是,它显然没有更新的时间包(我不熟悉旧的时间函数,所以这可能需要几个小时,因为它使用了
toutchtime

+1来显示如何尽可能减少“不纯净部分”。非常感谢你的链接,我终于可以更好地理解monads了。哈斯克尔在学校的教学方式完全令人困惑。
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