haskell - 在 Haskell 中调试时打印时间戳

标签 haskell io bind

我仍在学习 Haskell 并调试一些函数,并且通常有一个时间戳函数来了解某些操作何时开始和停止:

doSomeAction :: String -> IO ()
doSomeAction arg1 = do
  putStrLn =<< makeTime
  theThingthatTakesAwhile arg1
  putStrLn =<< makeTime
  where
    makeTime = (formatTime defaultTimeLocale "%Y%m%d%H%M%S") <$> getZonedTime

是我的=<<where包含 <$> 的子句与 IO 交互的合理方式 getZonedTime

λ> :t getZonedTime
getZonedTime :: IO ZonedTime

或者这是否会误导我或读者或者不符合惯用语?

输出是:

20170114152312
Doing some long function....
20170114152336

这正是我想看到的——它告诉我我需要什么。 putStrLn =<< something 看起来很奇怪以获得这种效果。

最佳答案

你的代码完全没问题。任何精通 Haskell 的程序员都应该很快就能理解它。

不过,按照我自己的风格,我更喜欢在 do block 中使用 let:

doSomeAction :: String -> IO ()
doSomeAction arg1 = do
  let makeTime = formatTime defaultTimeLocale "%Y%m%d%H%M%S" <$> getZonedTime
  putStrLn =<< makeTime
  theThingthatTakesAwhile arg1
  putStrLn =<< makeTime

或者可能是一些变化

doSomeAction :: String -> IO ()
doSomeAction arg1 = do
  let printTime = putStrLn . formatTime defaultTimeLocale "%Y%m%d%H%M%S" =<< getZonedTime
  printTime
  theThingthatTakesAwhile arg1
  printTime

但是,这只是个人喜好问题。

关于haskell - 在 Haskell 中调试时打印时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41655218/

相关文章:

haskell - 如何将字符串中的字符组合一次?

c - 使用 fwrite 将结构数组写入二进制文件

python - Python 3 中单元测试的预设输入

java - 为什么打印者将我的信息分成两个字符串?

c++ - 与 std::bind 相反,为函数添加虚拟参数

haskell - Emacs 24.1 和 haskell 模式键绑定(bind)

haskell - 带中缀符号的无点样式

haskell - 在 Haskell(GHC) 中快速检查一个讨厌的外部函数

java - 如何使用 Monadic Bind 简化此 Apache Tomcat 代码?

sockets - 为什么不允许将套接字精确绑定(bind)到多个端口?