我正在尝试编写一个相当简单的处理器模拟器,并试图将实际处理器与其内存接口分开。例如,旧的 TRS-80 有 12K 的 ROM,可以配置总共 16、32 或 48K 的总 RAM。我最初对内存系统的想法是一个类型类:
class MemorySystem memInternals addrType wordType where
-- | General memory fetch. This always returns a 'wordType' value,
-- even if the system's memory internals are byte addressable.
mfetch :: addrType -- ^ The address from which the instruction will be fetched
-> memInternals -- ^ The memory system
-> wordType -- ^ The fetched word
-- | Fetch a block of words from the memory system
mfetchN :: ( Unbox wordType
) =>
addrType -- ^ The address from which the instruction will be fetched
-> Int -- ^ Number of words to fetch
-> memInternals -- ^ The memory system
-> Vector wordType -- ^ The words fetched
澄清:重点MemorySystem
是允许指令解码器(例如,在 TRS-80 的情况下为 Z80 指令解码器)独立于其内存接口运行,这样解码器所需要做的就是调用mfetch
下一条指令及其操作数。因此,memInternals
是一种实现与部分由类型类函数指定的内存系统的接口的类型。
如何是最好的约束方式addrType
,wordType
同时允许memInterals
多态,即允许memInternals
表示不同的内存配置。我发现自己正在向看起来像这样的函数添加上下文:
foo :: ( MemorySystem memSys Word16 Word8) =>
-> memSys
-> Word16
-> Word16
bar :: ( MemorySystem memSys Word16 Word8) =>
-> memSys
-> Word16
-> Word8
bar mem pc = ...
-- bar calls foo -> rigid type variable error...
这会导致 ghc 中出现很多刚性类型变量错误。
是否有更好的方法来表达 a MemorySystem
,从而导致多态的“正确类型”,memInternals
以便可以正确表示内存接口系列(并通过类型类或系列对其进行操作)?