haskell

时间:2018-03-20 22:30:47

标签: haskell

我正在尝试编写一个基于3条指令的程序

在haskell中,它们看起来像这样。

-- DEL b        == empty box b

-- ADD b        == increment box b by 1

-- JEQ b1 b2 j  == if boxes b1 and b2 contain the same value, jump to instruction n

data Instruction
  = DEL {box :: Int} 
  | ADD {box :: Int}
  | JEQ {box1   :: Int, 
         box2   :: Int,
         jumpTo :: Int}
  deriving (Eq, Show)

type Program = [Instruction]

用户将输入一个表示从box1开始的框的值的起始列表,其中box0被留出用于计算目的。

e.g. 
boxes = [0, 4, 6, 5, 12, 20]

我已经编写了关于程序执行时盒子如何变化的代码,例如:

pgrm = [ADD 1, DEL 3, ADD 1, JEQ 1 2 4, CLR 4, ADD 4]

当在框上执行pgrm时,结果将是

[0, 6, 6, 0, 13, 20] 

但我现在正尝试使用给出的3条指令来实现加法器和复制程序。

-- Adds contents of box x and box y and puts it into box 1
addXY :: Int -> Int -> Program

-- copy the contents of box x to box y (leave box x unchanged)
copyBox :: Int -> Int -> Program

有没有办法可以在不更改任何其他框中的值的情况下实现这些,并且只使用带有空box0的3条指令来进行计算?怎么会这样呢?

PS。我知道这更像是一个数学理论问题而不是编码问题。如果有任何数学天才可以帮助我,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

  

有没有办法在不改变任何其他方框中的值的情况下实现这些

复制程序很简单。您可以将方框0用作计数器,并通过创建一个循环来复制该值,该循环在将目标框重置为零后递增目标框x次。实现循环时出现一个问题:您需要无条件跳转指令或带有否定条件的条件跳转。

示例1:您可以通过比较计数器和目标框来模拟无条件跳转,它们在循环中始终具有相同的值:

copyBox :: Int -> Int -> Program
copyBox x y = [ DEL 0      -- 0: clear box 0, we use it as a counter
              , DEL y      -- 1: clear destination box
              , JEQ 0 x 6  -- 2: counter reaches value in x => copying is finished
              , ADD 0      -- 3: increment counter
              , ADD y      -- 4: increment destination
              , JEQ 0 y 2  -- 5: always true, hence jump back to beginning of loop
              , DEL 0      -- 6: clear box 0 to clean up
              ]

示例2:这是一个变体,它使用假设的JNEQ指令:

copyBox :: Int -> Int -> Program
copyBox x y = [ DEL 0      -- 0: clear box 0, we use it as a counter
              , DEL y      -- 1: clear destination box
              , JEQ 0 x 6  -- 2: x is zero => skip the copy loop
              , ADD 0      -- 3: increment counter
              , ADD y      -- 4: increment destination
              , JNEQ 0 x 3 -- 5: counter not equal x => one more iteration
              , DEL 0      -- 6: clear box 0 to clean up
              ]

对于addXY例程,您需要此JNEQ指令或 - 如果您使用第一个示例的仿真技巧 - 另一个临时工作单元。我目前认为不可能使用提供的三条指令实现addXY,并且不会修改除0(临时)和1(结果)之外的任何框。

相关问题