2016年8月10日水曜日

開発環境

7つの言語 7つの世界 (Bruce A. Tate (著)、まつもとゆきひろ (監訳)、田和 勝 (翻訳)、オーム社)の第8章(Haskell)、8.4(3日目: 精神融合)、セルフスタディ3日目を取り組んでみる。

セルフスタディ3日目.

コード(Emacs)

module Main where

main = do
  print $ go node
  print $ go node1
  
data Exit = North | South | East | West deriving (Show, Eq)
data Node = Node  (Int, Int) [Exit] deriving (Show)
type Maze = [[Node]]

north (Node (a, b) xs) = if North `elem` xs
                         then Just $ maze !! (a - 1) !! b
                         else Nothing
south (Node (a, b) xs) = if South `elem` xs
                         then Just $ maze !! (a + 1) !! b
                         else Nothing
east (Node (a, b) xs) = if East `elem` xs
                        then Just $ maze !! a !! (b + 1)
                        else Nothing
west (Node (a, b) xs) = if West `elem` xs
                        then Just $ maze !! a !! (b - 1)
                        else Nothing

maze = [[Node (0, 0) [South, East],  Node (0, 1) [South, West]],
        [Node (1, 1) [North, South], Node (1, 1) [North, South]],
        [Node (2, 1) [North, South], Node (2, 1) [North, South]],
        [Node (3, 1) [North, South], Node (3, 1) [North, South]],
        [Node (4, 1) [North],        Node (4, 1) [North, East],
         Node (4, 2) [West]]]
  
go node = Just node >>=
          east >>=
          south >>=
          south >>=
          south >>=
          south >>=
          east >>=
          return

node = maze !! 0 !! 0
node1 = maze !! 0 !! 1

入出力結果(GHCI, Terminal, REPL(Read, Eval, Print, Loop))

$ runghc maze.hs
Just (Node (4,2) [West])
Nothing
$

0 コメント:

コメントを投稿