Value Limitations

Suppose we have the following data type:

data Cmd = Cmd0 Opcode | Cmd1 Opcode Arg | Cmd2 OPcode Arg Arg data Opcode = NOP | INC | ADD | MUL deriving (Enum) data Arg = W32 Int | W16 Int | W8 Int 

The idea is to have an Opcode type that generates opcode serial numbers. Is there a way to specify restrictions for Cmd values, say: Cmd0 has only NOP operation code, Cmd1 has only INC, Cmd2 has only ADD or MUL values. I tried to use GATD, but they work by types, not values.

Or vice versa, is there a way to generate sequential operation codes for each Cmd value without declaring the Enum method for each value manually or without using TH?

+6
source share
1 answer

You can use separate OpCode types:

 data Opcode0 = NOP data Opcode1 = INC data Opcode2 = ADD | MUL data Cmd = Cmd0 Opcode0 | Cmd1 Opcode1 Arg | Cmd2 Opcode2 Arg Arg 

Now sometimes you can consider all Opcodes as one type, say, to put them on a list. To do this, you can use the type class for Opcode types and use existential types :

 class OpcodeCl a where --empty classes seem to be allowed (in GHC at least) instance OpcodeCl Opcode0 where instance OpcodeCl Opcode1 where instance OpcodeCl Opcode2 where data Opcode = forall a . (OpcodeCl a) => Op { unOp :: a } 

I suspect you cannot do anything with OpCode here, since the OpcodeCl class has no methods. You can add useful methods to OpcodeCl that convert to or from Int s, for example.

+8
source

Source: https://habr.com/ru/post/903037/


All Articles