PureScriptで作るBrainfuckインタプリタ 3/4 CUIでの可視化
動作の可視化 インタプリタ動作中における内部状態を可視化できると面白い。 そこで、インタプリタ動作中のログを出力できるような仕組みを作る。 ログは以下のタイミングで起こるようにする。 onStart: インタプリタが動作したときに起こる。 onState state: 各ステップで状態を取得したときに起こる。 onCmd cmd: 各ステップで命令を取得できたときに起こる。 onEnd: インタプリタが終了するときに起こる。 これらはイベントリスナのように、関数の形で指定する。 Logの作成 src/Brainfuck/Interp/Log.pursを作成。 以下のimport文を書く。 1 2 3 4 5 6 7 8 9 module Brainfuck.Interp.Log where import Prelude import Brainfuck.Interp (Interp) import Brainfuck.State (State) import Brainfuck.Command (Command) import Effect.Class (class MonadEffect, liftEffect) import Effect.Console (log) Logを定義。 1 2 3 4 5 6 newtype Log m = Log { onStart :: Interp m Unit , onState :: State -> Interp m Unit , onCmd :: Command -> Interp m Unit , onEnd :: Interp m Unit } 関連する関数を定義。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 logStart :: forall m. Log m -> Interp m Unit logStart (Log { onStart }) = onStart logState :: forall m. Log m -> State -> Interp m Unit logState (Log { onState }) = onState logCmd :: forall m. Log m -> Command -> Interp m Unit logCmd (Log { onCmd }) = onCmd logEnd :: forall m. Log m -> Interp m Unit logEnd (Log { onEnd }) = onEnd いくつかのLog mを作っておく。 ...