哈斯克尔练习解构记录语法



开始练习以复习所学的Haskell技能。

module Clock (addDelta, fromHourMin, clockDecons) where
data Clock = Clock { hours :: Int 
                   , mins  :: Int 
                   } deriving Show 
fromHourMin :: Int -> Int -> Clock
fromHourMin hour min = Clock {hours = hour, mins = min}
-- toString :: Clock -> String
clockDecons clock = (hs,ms) 
  where hs = hours 
        ms = mins
addDelta :: Int -> Int -> Clock -> Clock
addDelta hour min clock = undefined

一整天后可能会有点阴云,但为什么我会得到:

<interactive>:15:1: error:
    • No instance for (Show (Clock -> Int))
        arising from a use of ‘print’
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it

我甚至还没有开始创建时钟的字符串实例。

你可能的意思

clockDecons :: Clock -> (Int, Int)
clockDecons clock = (hours clock, mins clock) 

备选方案:

clockDecons :: Clock -> (Int, Int)
clockDecons (Clock hs ms) = (hs, ms) 

另类:

clockDecons :: Clock -> (Int, Int)
clockDecons Clock{hours=hs, mins=ms} = (hs, ms) 

替代方案:根本不使用任何clockDecons。您实际上是在 Clock 构造函数下解开两个整数,以将它们重新包装在对的(,)构造函数下。这不是decons.保持时钟值换行,直到您实际需要解构它。

最新更新