Rewriting code with continuations

前端 未结 1 542
旧时难觅i
旧时难觅i 2021-01-03 04:43

I have some code that evaluates primitive programs. Program is a list of statements (expression, block, return statement). Result of evaluation is last evaluated expression.

相关标签:
1条回答
  • 2021-01-03 05:02

    The translation is fairly mechanical.

    Keep in mind that in the continuation monad, return feeds the value into the continuation.

    evalStmt :: Statement -> Cont Value Value
    evalStmt (Expr val) = 
        let res = Value val
        in return res
    evalStmt (Block stmts) = evalBlock stmts
    evalStmt (Return val) = cont $ \_ -> Value val
    
    evalBlock :: [Statement] -> Cont Value Value
    evalBlock [] = return Undefined
    evalBlock [st] = evalStmt st
    evalBlock (st:rest) = evalStmt st >> evalBlock rest
    
    evalProgram :: [Statement] -> Value
    evalProgram stmts = runCont (evalBlock stmts) id
    

    And to simulate early returns, we just ignore the continuation given to Return val and just return the value we have.

    0 讨论(0)
提交回复
热议问题