haskell branchz int,jump int和mark int stack

时间:2014-06-03 00:39:36

标签: haskell stack branch

--my datatypes
data Command =PushK Int | Mark Int | Jump Int | Branchz Int deriving (Eq,Show)
type Program = [Command]
type Stack = [Int]

interpret::Program -> Stack 
interpret = interpret [] where
    interpret stack []                      = stack
    interpret stack ( PushK n:xs)           =interpret (n:stack)xs
    interpret stack (Mark n:xs)             =interpret stack xs

Interpret(Branchz n:xs) (a:b)  =if(0 ==a) then interpret (dropWhile (n /= )Program) b  program else interpret xs b program

Interpret (Jump n :xs) stack = Interpret(dropWhile(n/=)program) stack program

我现在需要解释Branchz Int和Jump Int,但我不知道如何在第二部分中获取程序代码。

1 个答案:

答案 0 :(得分:1)

好的,那很接近:

data Command = PushK Int | Mark Int | Jump Int | Branchz Int deriving (Eq,Show)
type Program = [Command]
type Stack = [Int]

interpret :: Program -> Stack 
interpret program = interpret_ [] program
  where
    interpret_ stack []             = stack
    interpret_ stack (PushK n:xs)   = interpret_ (n:stack) xs
    interpret_ stack (Mark n:xs)    = interpret_ stack xs
    interpret_ (a:b) (Branchz n:xs) = 
      if (0 == a) then 
        interpret_ b (skip (n/=) program)
      else 
        interpret_ b xs
    interpret_ stack (Jump n:xs)    = interpret_ stack (skip (n/=) program)
    skip f (Mark a:b) = if not (f a) then b else skip f b
    skip f (_:b)      = skip f b

interpret的定义中,您没有指定参数的名称(要解释的Program),这是在“倒带”时能够引用它的必要条件,即。以dropWhile寻求的位置递归调用解释器,我在此处用skip替换。