Chapter 05

一命令の実行

Nobuo Yamashita
Nobuo Yamashita
2021.12.03に更新
このチャプターの目次

Toy.step の実装 (toy04)

step は一命令の実行を行います。一命令の実行は、フェッチ-デコード-実行で構成されます。

step :: ToyState -> ToyState
step state = execute (decode (fetch state)) state

フェッチは、次に実行する命令コードを読み出します。

fetch :: ToyState -> Code
fetch = undefined

デコードは命令コードを解釈して、命令 Instruction を構成します。

type Instruction = ToyState -> ToyState

decode :: Code -> Instruction
decode = undefined

実行は命令を現在の状態に適用して次の状態を構成します。単にデコードされた命令を適用するだけですので、なにもしない恒等関数 id とすればよいでしょう。

execute :: Instruction -> ToyState -> ToyState
execute = id

コード

ここまでのToyモジュール
src/Toy.hs
module Toy where

type SourceCode  = String
type Interactive = [Input] -> [Output]
type Input  = String
type Output = String

drive :: Interactive -> (String -> String)
drive f = unlines . f . lines

toy :: SourceCode -> Interactive
toy prog = map output . eval . initState (load prog)

output :: ToyState -> Output
output = undefined

load :: SourceCode -> Memory
load = undefined

initState :: Memory -> [Input] -> ToyState
initState = undefined

type Memory   = ()
type ToyState = ()

eval :: ToyState -> [ToyState]
eval state = state : rests
    where
        rests | isFinal state = []
              | otherwise     = eval (step state)

isFinal :: ToyState -> Bool
isFinal = undefined

type Instruction = ToyState -> ToyState

step :: ToyState -> ToyState
step state = execute (decode (fetch state)) state

fetch :: ToyState -> Code
fetch = undefined

decode :: Code -> Instruction
decode = undefined

execute :: Instrunction -> Instruction
execute = id