Haskell练习解构记录语法

Haskell Exercise deconstructing record syntax

开始练习以复习所学 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。保持时钟值包装,直到您真正需要解构它。