Langton's ant: Difference between revisions

(add scala)
Line 782:
A straightforward implementation (assumes that we start with ant looking forward):
 
<lang ela>open list variantcore generic
 
type Field = Field a
field s = Field [[White \\ (_) <- [1..s]] \\ (_) <- [1..s]]
type Color = White | Black
type Direction = Lft | Fwd | Rgt | Bwd
field s = Field [[White \\ (_) <- [1..s]] \\ (_) <- [1..s]]
 
isBlack Black = true
isBlack _ = false
 
newfield xc yc (Field xs) = Field (newfield' 0 xs)
where newfield' _ [] = []
newfield' n (x::xs) | n == yc = row 0 x :: xs
| n == yc = row | else =0 x :: newfield' (n+1) xs
| else = x :: newfield' (n+1) where row _ [] = []xs
where row n_ (x::xs) | n[] == xc = toggle x :: xs[]
row n | else = (x :: row (n+1xs) xs
| n == xc where= toggle Whitex =:: Blackxs
| else = x :: row (n+1) toggle Black = Whitexs
where toggle White = Black
 
toggle Black = White
showPath (Field xs) = show' xs
where show' [] = ""
showPath (Field show' (x::xs) = showRowtoString x ++ "\r\n" ++<| show' stringBuilder xs
where show' where showRowsb [] = sb +> ""
show' showRowsb (x::xs) = sshow' (showRow sb x ++> showRow"\r\n") xs
where sshowRow |sb x[] `tagged`= Whitesb =+> "_"
showRow sb (x::xs) = showRow (sb +> s) | else = "#"xs
where show's | isBlack []x = "#"
 
| else = "_"
move s xc yc = move' (Fwd,xc,yc) (field s)
where move' (pos,xc,yc)@coor fld | xc >= s or yc >= s or xc < 0 or yc < 0 = fld
| xc >= s or yc >= s or xc < 0 or yc < | isBlack fld0 = fld |> newfield xc yc |> move' (matrix Lft coor)
| else = fld |> newfield xc yc |> move' (matrix Rgt(dir fld) coor)
where isBlackdir (Field xs) = (xs:yc):xc `tagged` Black
| matrix Lft`isBlack` (pos,x,yxs:yc):xc = go (left pos,x,y)Lft
| else matrix= Rgt (pos,x,y) = go (right pos,x,y)
matrix goLft (Lftpos,x,y) = go (Lftleft pos,x-1,y)
matrix goRgt (Rgtpos,x,y) = go (Rgtright pos,x+1,y)
go (FwdLft,x,y) = (FwdLft,x-1,y-1)
go (BwdRgt,x,y) = (BwdRgt,x+1,y+1)
go right Lft(Fwd,x,y) = (Fwd,x,y-1)
go right Fwd(Bwd,x,y) = Rgt(Bwd,x,y+1)
right RgtLft = BwdFwd
right BwdFwd = LftRgt
right left LftRgt = Bwd
leftright Bwd = RgtLft
left RgtLft = FwdBwd
left FwdBwd = Lft</lang>Rgt
left Rgt = Fwd
left Fwd = Lft</lang>
 
This implementation is pure (doesn't produce side effects).
Anonymous user