【发布时间】:2012-02-03 06:04:52
【问题描述】:
在这个 Haskell 代码中,构造函数参数(长度和宽度)可以是任何数据类型(如 Int、Char 等)。有没有一种方法可以明确指定长度和宽度的数据类型? 如何指定函数getLength的返回类型?
{-# LANGUAGE EmptyDataDecls, DeriveDataTypeable, TemplateHaskell #-}
{-# OPTIONS_GHC -fcontext-stack=100 #-}
module Rectangle where
import OOHaskell
$(label "getLength")
$(label "getWidth")
$(label "incr")
$(label "lengthenBy")
$(label "setLength")
$(label "setWidth")
$(label "show'")
rectangle length width self
= do
lengthRef <- newIORef length
widthRef <- newIORef width
return $
getLength .=. readIORef lengthRef
.*. getWidth .=. readIORef widthRef
.*. setLength .=. writeIORef lengthRef
.*. setWidth .=. writeIORef widthRef
.*. lengthenBy .=. (\dl ->
do
length <- self # getLength
(self # setLength) (length + dl))
.*. incr .=. (self # lengthenBy) (1)
.*. show' .=. printLn ("Length : "<< self # getLength<<" Width : "<< self # getWidth)
.*. emptyRecord
如果主要写成这样,它应该可以工作(它是):
main = do
c1 <- mfix $ rectangle 0 0
c2 <- mfix $ rectangle 0 0
c3 <- mfix $ rectangle 0 0
c1# setWidth $ 3
c2# setWidth $ 2
c3# setWidth $ 2
c1# incr
c2# incr
c1# incr
c1# show'
c3# show'
但是 main 是可以工作的,即使它是这样写的,这是不受欢迎的(因为宽度不能是一个字符)。
main = do
c1 <- mfix $ rectangle 0 'a'
c2 <- mfix $ rectangle 0 'b'
c3 <- mfix $ rectangle 0 'c'
c1# setWidth $ 'd'
c2# setWidth $ 'e'
c3# setWidth $ 'f'
c1# incr
c2# incr
c1# incr
c1# show'
c3# show'
【问题讨论】:
标签: haskell