문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top