型、型クラスとMaybe
亀プログラムに向けて型と型クラスの練習。go/left/rightだけ考えてみる。
型クラスはJavaでいうトコロのインタフェースに相当する。型クラスの関数を実装してインスタンス化。
ムリヤリMaybeも入れてみるが、そのせいなのかなんなのかいまいちピンと来ず。
ダメなトコロ
- t_parseは[String]を渡すが、リストの先頭のStringしかパースしない。
- t_parseの第1引数が空リストのとき実行できない
import Maybe class Node a where t_exec :: a -> (Int, Int) -> (Int,Int) t_parse :: [a] -> [String] -> Maybe [a] data PrimCmdNode = GoCmdNode | LeftCmdNode | RightCmdNode t_go = GoCmdNode t_left = LeftCmdNode t_right = RightCmdNode instance Show PrimCmdNode where show GoCmdNode = show "go_cmd_node" show LeftCmdNode = show "left_cmd_node" show RightCmdNode = show "rigth_cmd_node" instance Node PrimCmdNode where t_exec GoCmdNode (a,b) = (a,b+1) t_exec LeftCmdNode (a,b) = (a-1,b) t_exec RightCmdNode (a,b) = (a+1,b) t_parse [a] [] = Just [a] t_parse [a] (x:xs) = case x of "go" -> Just ([a]++[t_go]) "left" -> Just ([a]++[t_left]) "right" -> Just ([a]++[t_right]) _ -> Nothing {----------- テスト用 -----------} testWords = ["go","left","right","left","go","left","right"] testExec = t_exec t_right (1,1) testShow = map show [t_go, t_left, t_right, t_left, t_right, t_right]