5 from Text import class Text, instance Text String
7 from Data.Func import $
11 import Control.Monad.RWST
12 import Control.Applicative
16 :: Coord :== (Int, Int)
17 :: Position = Inv | Emp | Peg
18 :: PegBoard :== {{Position}}
19 :: Move :== (Coord, Direction)
20 :: Direction = N | E | S | W
21 :: Solver a :== RWST () [PegBoard] PegBoard Maybe a
25 {{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
26 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
27 ,{Peg, Peg, Peg, Peg, Peg, Peg, Peg}
28 ,{Peg, Peg, Peg, Emp, Peg, Peg, Peg}
29 ,{Peg, Peg, Peg, Peg, Peg, Peg, Peg}
30 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
31 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
34 empty = RWST $ \_ _->Nothing
35 (<|>) (RWST fa) (RWST fb) = RWST $ \r s->case fa r s of
39 instance toChar Position where
40 toChar p = case p of Inv = ' '; Emp = '.'; Peg = 'o'
42 instance == Position where
48 transform :: Coord Direction -> Coord
49 transform (x, y) d = case d of N = (x, y+1); S = (x, y-1); W = (x+1, y); E = (x-1, y)
51 getPos :: Coord -> Solver Position
52 getPos c=:(x, y) = get >>= \b->if (valid b) empty (pure b.[y].[x])
54 valid b = y<0 || x<0 || y >= size b || x >= size b.[0] || b.[y].[x] == Inv
56 applyMove :: Move -> Solver ()
57 applyMove (tc=:(tx, ty), d)
58 # sc=:(sx, sy) = transform tc d
59 # fc=:(fx, fy) = transform sc d
60 = get >>= \b->liftM3 tuple3 (getPos fc) (getPos sc) (getPos tc) >>= \f->case f of
62 # b = {{{c\\c<-:r}\\r<-:b} & [fy,fx]=Emp, [sy,sx]=Emp, [ty,tx]=Peg}
66 getCoords :: (Position -> Bool) PegBoard -> [Coord]
67 getCoords f b = [(x, y)\\r<-:b & y<-[0..] , c<-:r & x<-[0..] | f c]
69 win :: (PegBoard -> Bool)
70 win = (==) 1 o length o getCoords ((==)Peg)
72 printPegBoard :: PegBoard -> String
73 printPegBoard b = 'Text'.join "\n" ["\n":[{#toChar x\\x<-:r}\\r <-: b]]
75 getMoves :: Solver [Move]
76 getMoves = gets (\b->[(c,d)\\c<-getCoords ((==)Emp) b, d<-[N,E,S,W]])
78 solve :: PegBoard -> Maybe [PegBoard]
79 solve b = snd <$> evalRWST (tell [b] >>| solver) () b
81 solver = get >>= \board->case win board of
82 True = get >>= \b->tell [b]
84 >>= foldr (<|>) empty o map (\m->applyMove m >>| solver)
86 Start = 'Text'.join "\n" o map printPegBoard <$> solve european