このチャプターの目次
Memory
と ToyState
(toy05)
メモリ Memory
は、メモリ位置を示すラベルがついた、命令あるいはデータのリストとして表現します。
type Label = String
type Memory = [(Label, Content)]
Content
はプログラムコードあるいはデータ数値としましょう。
data Content
= Code Code
| Data Int
トイ・マシンの状態、ToyState
は、
- 停止状態かどうかのフラッグ
Final
- メモリ
Memory
- アキュムレータ
Acc
- 入力リスト
[Input]
- 出力
Output
の5つ組としておきましょう。
type ToyState = (Final, Memory, Acc, [Input], Output)
type Final = Bool
type Acc = Int
終了状態かどうかを判定する isFinal
は Final
フラッグを確認すればよいので、そのように実装をしてしまいます。
isFinal :: ToyState -> Bool
isFinal state@(flg,_,_,_,_) = flg
コード
ここまでの 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 = [(Label, Content)]
type Label = String
data Content
= Code Code
| Data Int
type ToyState = (Final, Memory, Acc, [Input], Output)
type Final = Bool
type Acc = Int
eval :: ToyState -> [ToyState]
eval state = state : rests
where
rests | isFinal state = []
| otherwise = eval (step state)
isFinal :: ToyState -> Bool
isFinal state@(flg,_,_,_,_) = flg
step :: ToyState -> ToyState
step state = execute (decode (fetch state)) state
type Instruction = ToyState -> ToyState
type Code = ()
fetch :: ToyState -> Code
fetch = undefined
decode :: Code -> Instruction
decode = undefined
execute :: Instruction -> ToyState -> ToyState
execute = id