1

I declare some data type as follow:

data TX_OR_TY = TX | TY
data TX = X Int
data TY = Y Float

Now I write some function return their data type:

funcTX :: TX
funcTX = X 3

funcTY :: TY
funcTY = Y 5

ordFuncTX :: TX -> Int -> Bool
ordFuncTX (X a) b = (a > b)

funcTX_TY :: TX_OR_TY
funcTX_TY = if (ordFuncTX funcTX 4) then funcTX else funcTY

Function funcTX_TY will return a type of TX_OR_TY by comparing the value of TX with 4, if bigger then return TX, if smaller then return TY. But when compiling, it announces that it couldn't match expected type TX_OR_TY with TX. How can I fix?

chipbk10
  • 5,783
  • 12
  • 49
  • 85

1 Answers1

5

Your data declarations are probably not what you intended.

TX_OR_TY just defines two constructors: TX and TY.

The following data declarations define the types TX and TY.

You probably meant something like

data TX_OR_TY = AnX TX | AnY TY
data TX = X Int
data TY = Y Float
-- Now I write some function return their data type:

funcTX :: TX
funcTX = X 3

funcTY :: TY
funcTY = Y 5

ordFuncTX :: TX -> Int -> Bool
ordFuncTX (X a) b = (a > b)

funcTX_TY :: TX_OR_TY
funcTX_TY = if (ordFuncTX funcTX 4) then AnX funcTX else AnX funcTY

Note that TX_OR_TY is a specialized version of the Either data type from the standard prelude. To use Either, omit the definition of TX_OR_TY and change the function thus:

funcTX_TY :: Either TX TY
funcTX_TY = if (ordFuncTX funcTX 4) then Left funcTX else Right funcTY
Chris
  • 4,133
  • 30
  • 38
  • If I declare like data TX_OR_TY = X Int | Y Float. It will be ok. But sometime TX and TY I would like to declare them separately in case TX and TY is a really complex type, and I don't want to declare in one line – chipbk10 Jan 07 '13 at 02:05
  • @chipbk10 declaring them separately is ok, and my example still uses your definitions of the TX and TY types. – Chris Jan 07 '13 at 02:11
  • data TX_OR_TY = TX TX | TY TY ---> what does this mean? It makes me more confused. – chipbk10 Jan 07 '13 at 02:20
  • I've renamed the type constructors in my example. Less confusing now? – Chris Jan 07 '13 at 02:23