Drkcore

22 07 2012 Haskell Tweet

Haskellで日付をあつかう

PLEACのレシピ9.1 タイムスタンプをHaskellで書いてみたんだけどちょっとめんどくさかった(Pythonも日付はめんどくさいけど)。

import System.Posix.Files
import System.Time
import System.Posix.Types
import System.Environment

getTimes :: FilePath -> IO (ClockTime, ClockTime)
getTimes fp =
    do stat <- getFileStatus fp
       return (toct (accessTime stat),
               toct (modificationTime stat))

toct :: EpochTime -> ClockTime
toct et = TOD (truncate (toRational et)) 0

main :: IO ()
main = do
  (file:_) <- getArgs
  (atime, mtime) <- getTimes file
  print atime
  print mtime

getFileStatus関数で時間の情報はEpochTime型が返ってくるので、これをClockTime型に変換する

type EpochTime = CTime

EpochTimeはCTimeの別名なんだけど、CTimeはRealのインスタンスなのでtoRationalで有理数に変換してtruncateを通してIntegerに。

これをClockTime型のデータコンストラクタであるTODに通す。

ClockTime型の出力は

Sun Jul 22 09:10:59 JST 2012

もう少し細かく制御したい場合にはtoCalendarTime関数でCalendarTIme型に変換して望みのフォーマットにすればいい。

RWHの20.4にきちんと書いてあった。

ProductName Real World Haskell―実戦で学ぶ関数型言語プログラミング
Bryan O'Sullivan
オライリージャパン / 3990円 ( 2009-10-26 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021