当前位置: 动力学知识库 > 问答 > 编程问答 >

Specify Data type In OO Haskell

问题描述:

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 getLength will match the contents of lengthRef, so you just need to add a type signature somewhere that constrains that type, and the type of getLength should be inferred correctly from that.

For example, you can specify the type when creating lengthRef:

lengthRef <- newIORef (length :: Int)
网友答案:

Is there a way by which i can explicitly specify the data type of length and width?

yes:

rectangle :: TypeOfLength -> TypeOfWidth -> TypeOfSelf -> ReturnTypeOfRectangle
rectangle length width self = ...

How can i specify the return type of function getLength?

I never use OOHaskell so I'm not sure about this. Basically, you could declare types that a function expects (as arguments) and its return type. The syntax is like rectangle above, return type is always the right most one.

Reference: http://en.wikibooks.org/wiki/Haskell/Type_basics#Type_signatures_in_code

网友答案:

You could always add type annotations to your constructor, for example when you create the IORefs, something like:

widthRef :: IORef Int <- newIORef width

Or the equivalent on the function argument width itself.

分享给朋友:
您可能感兴趣的文章:
随机阅读: