optimalisation
[cleanpeg.git] / peg.icl
1 module peg
2
3 import StdEnv
4
5 from Text import class Text, instance Text String
6 import qualified Text
7 from Data.Func import $
8 import Data.Tuple
9 import Data.List
10 import Data.Monoid
11 import Control.Monad
12 import Control.Monad.RWST
13 import Control.Applicative
14 import Data.Maybe
15 import Data.Functor
16
17 :: Position :== Char
18 Inv :== ' '
19 Emp :== '.'
20 Peg :== 'o'
21
22 :: Direction :== Int
23 N :== 0
24 E :== 1
25 S :== 2
26 W :== 3
27
28 :: Coord = {x::Int, y::Int}
29 :: Move = {c::Coord, d::Direction}
30 :: PegBoard :== {{#Position}}
31
32 :: Solver a :== RWST () [PegBoard] PegBoard Maybe a
33
34 european :: PegBoard
35 european =
36 {{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
37 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
38 ,{Peg, Peg, Peg, Peg, Peg, Peg, Peg}
39 ,{Peg, Peg, Peg, Emp, Peg, Peg, Peg}
40 ,{Peg, Peg, Peg, Peg, Peg, Peg, Peg}
41 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
42 ,{Inv, Inv, Peg, Peg, Peg, Inv, Inv}
43 }
44
45 empty = RWST \_ _->Nothing
46 (<|>) (RWST fa) (RWST fb) = RWST \r s->maybe (fb r s) Just (fa r s)
47
48 transform :: Coord Direction -> Coord
49 transform c=:{x,y} d = case d of
50 N = {c&y=y+1}; S = {c&y=y-1}; W = {c&x=x+1}; E = {c&x=x-1}
51
52 getPos :: Coord -> Solver Position
53 getPos {x,y} = get >>= \b->if (valid b) empty (pure b.[y].[x])
54 where
55 valid b = y<0 || x<0 || y >= size b || x >= size b.[0] || b.[y].[x] == Inv
56
57 move :: Move -> Solver ()
58 move {c=c=:{x=tx,y=ty}, d}
59 # sc=:{x=sx,y=sy} = transform c d
60 # fc=:{x=fx,y=fy} = transform sc d
61 = get >>= \b->liftM3 tuple3 (getPos fc) (getPos sc) (getPos c) >>= \f->case f of
62 (Peg, Peg, Emp)
63 # b = {{{c\\c<-:r}\\r<-:b} & [fy,fx]=Emp, [sy,sx]=Emp, [ty,tx]=Peg}
64 = tell [b] >>| put b
65 _ = empty
66
67 getCoords :: (Char -> Bool) PegBoard -> [Coord]
68 getCoords f b = [{x=x,y=y}\\r<-:b & y<-[0..] , c<-:r & x<-[0..] | f c]
69
70 win :: (PegBoard -> Bool)
71 win = (==) 1 o length o getCoords ((==)Peg)
72
73 printPegBoard :: PegBoard -> String
74 printPegBoard b = 'Text'.join "\n" [r\\r <-: b]
75
76 moves :: Solver [Move]
77 moves = gets $ \b->[{c=c,d=d}\\c<-getCoords ((==)Emp) b, d<-[N,E,S,W]]
78
79 solve :: PegBoard -> Maybe [PegBoard]
80 solve b = snd <$> evalRWST (tell [b] >>| solver) () b
81 where
82 solver = get >>= \board->if (win board)
83 (get >>= tell o pure)
84 (moves >>= foldr (<|>) empty o map (\m->move m >>| solver))
85
86 Start = 'Text'.join "\n" o map printPegBoard <$> solve european