Langton's ant: Difference between revisions

Line 782:
A straightforward implementation (assumes that we start with ant looking forward):
 
<lang ela>open Corelist variant
 
let field s = Field [[White \\ (_) <- [1..s]] \\ (_) <- [1..s]]
 
let newfield xc yc (Field xs) = Field (newfield' 0 xs)
where newfield' _ [] = []
newfield' n (x::xs) | n == yc = row 0 x :: xs
| else = x :: newfield' (n+1) xs
where row _ [] = []
row n (x::xs) | n == xc = toggle x :: xs
| else = x :: row (n+1) xs
where toggle White = Black
toggle Black = White
 
let extends showshowPath (Field xs) = show' xs
where show' [] = ""
show' (x::xs) = showRow x ++ "\r\n" ++ show' xs
where showRow [] = ""
showRow (x::xs) = s ++ showRow xs
where s | x is`tagged` White = "_"
| else = "#"
 
let 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
| isBlack fld = fld |> newfield xc yc |> move' (matrix Lft coor)
| else = fld |> newfield xc yc |> move' (matrix Rgt coor)
where isBlack (Field xs) = (xs:yc):xc is`tagged` Black
et matrix Lft (pos,x,y) = go (left pos,x,y)
matrix Rgt (pos,x,y) = go (right pos,x,y)
et go (Lft,x,y) = (Lft,x-1,y)
go (Rgt,x,y) = (Rgt,x+1,y)
go (Fwd,x,y) = (Fwd,x,y-1)
go (Bwd,x,y) = (Bwd,x,y+1)
et right Lft = Fwd
right Fwd = Rgt
right Rgt = Bwd
right Bwd = Lft
et left Lft = Bwd
left Bwd = Rgt
left Rgt = Fwd
left Fwd = Lft</lang>
</lang>
 
This implementation is pure (doesn't produce side effects).
Line 829 ⟶ 828:
Testing:
 
<lang ela>showshowPath <| move 100 50 50</lang>
 
Output (empty lines are skipped to save space):
Anonymous user