In this Haskell code the constructor arguments(length and width) can be of any data type (like Int,Char etc.). Is there a way by which i can explicitly specify the data type of length and width? How can i specify the return type of function 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
The main should work (which it is) if it is written like:
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'
But main is working even if it is written this way which is undesirable( as width cannot be a character).
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'
Assuming this is all type-safe, the return type of
getLengthwill match the contents oflengthRef, so you just need to add a type signature somewhere that constrains that type, and the type ofgetLengthshould be inferred correctly from that.For example, you can specify the type when creating
lengthRef: