Haskell:以一种很好的方式命名多个参数

时间:2018-03-20 13:49:10

标签: haskell

我正在为我的学校项目开发虚拟堆栈机器。一切正常,但这就是我作为程序运行的控制功能所具有的:

196.168.0.55:8081

这个run :: Program -> SubprogramDir -> Memory -> ComputerStack -> Input -> Output -> Output run EOP _ _ _ _ out = out run (lbl `Marks` prg) dir mem stack inp out = run prg dir mem stack inp out run (ins `Then` prg) dir mem stack inp out = case ins of (TA addr) -> (run prg dir mem (Stack.push (Left addr) stack) inp out) (TV val) -> (run prg dir mem (Stack.push (Right val) stack) inp out) DR -> (dr prg dir mem stack inp out) ST -> (st prg dir mem stack inp out) WR -> (wr prg dir mem stack inp out) RD -> (rd prg dir mem stack inp out) AD -> (mathAction (+) prg dir mem stack inp out) SB -> (mathAction (-) prg dir mem stack inp out) MT -> (mathAction (*) prg dir mem stack inp out) DI -> (mathAction (div) prg dir mem stack inp out) (JU lbl) -> (ju lbl prg dir mem stack inp out) (JZ lbl) -> (jz lbl prg dir mem stack inp out) 一直在重复,看起来很糟糕。有没有办法将它归为一个,比方说,元组,并将其传递给其他函数?还是以其他更好的方式来写它?

1 个答案:

答案 0 :(得分:4)

您可以定义帮助器call功能

run (ins `Then` prg) dir mem stack inp out =
  let call k = k prg dir mem stack inp out
  in case ins of
    TA addr -> (run prg dir mem (Stack.push (Left addr) stack) inp out) 
    TV val -> (run prg dir mem (Stack.push (Right val) stack) inp out)
    DR -> call dr
    ST -> call st
    WR -> call wr
    RD -> call rd
    AD -> call $ mathAction (+)
    SB -> call $ mathAction (-)
    MT -> call $ mathAction (*)
    DI -> call $ mathAction (div)
    JU lbl -> call $ ju lbl
    JZ lbl -> call $ jz lbl

将数据类型中的所有常见状态变量封装似乎更合适。通常,此执行状态称为抽象机器的“配置”。例如,

data Config = Config SubprogramDir Memory ComputerStack Input Output

还可以将其变成记录。