目前,我有一个WorkLog
类型,有开始和结束日期。我还想添加一个持续时间镜头,它将根据开始日期和结束日期得出。它应该是只读的,或者如果它的值发生变化则更改结束日期(我想知道如何实现这两个版本,即使我只会使用一个)。
这是我的代码。基本上,如果您可以实现workLogDurationRO
andworkLogDurationRW
函数以使所有测试通过主要测试,那将回答我的问题。
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Lens
-- Keep times simple for this example
newtype TimeStamp = TimeStamp Int deriving (Show, Eq)
newtype TimeDifference = TimeDifference Int deriving (Show, Eq)
(-.-) :: TimeStamp -> TimeStamp -> TimeDifference
(TimeStamp a) -.- (TimeStamp b) = TimeDifference (a - b)
data WorkLog = WorkLog {
_workLogDescription :: String
, _workLogStartTime :: TimeStamp
, _workLogEndTime :: TimeStamp
}
makeLenses ''WorkLog
-- | Just return the difference between the start and end time
workLogDurationRO :: Getter WorkLog TimeDifference
workLogDurationRO = error "TODO write me!"
-- | Like the read only version, but when used with a setter,
-- change the end date.
workLogDurationRW :: Lens' WorkLog TimeDifference
workLogDurationRW = error "TODO write me!"
ensure :: String -> Bool -> IO ()
ensure _ True = putStrLn "Test Passed"
ensure msg False = putStrLn $ "Test Failed: " ++ msg
main :: IO ()
main = do
let testWorkLog = WorkLog "Work 1" (TimeStamp 40) (TimeStamp 100)
ensure "read only lens gets correct duration" $
testWorkLog^.workLogDurationRO == TimeDifference 60
ensure "read+write lens gets correct duration" $
testWorkLog^.workLogDurationRW == TimeDifference 60
let newWorkLog = testWorkLog & workLogDurationRW .~ TimeDifference 5
ensure "writeable lens changes end time" $
newWorkLog^.workLogEndTime == TimeStamp 45