Haskell Exercise解构记录语法

时间:2019-07-08 16:07:45

标签: haskell record

开始锻炼以掌握已学过的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

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

2 个答案:

答案 0 :(得分:5)

您可能是想

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

答案 1 :(得分:3)

替代:

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。保留时钟值,直到您真正需要解构它为止。