Advertisement
Guest User

Untitled

a guest
May 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fun row_size mat = length mat;
  2. fun col_size [] = 0
  3. | col_size (m::mat) = length m;
  4.  
  5. fun valid_index mat (r,c) = if r<0 orelse r>((row_size mat)-1) orelse c<0 orelse c>((col_size mat)-1) then false else true;
  6.  
  7. fun is_alive [] _ = false
  8.     | is_alive (x::xs) (0,0) = if x=[] then false else hd(x)
  9.     | is_alive (x::xs) (0,y) = if (valid_index (x::xs) (0,y)) then hd(List.drop(x,y))
  10.                              else false
  11.     | is_alive (m::ms) (x,y) = if (valid_index (m::ms) (x,y)) then (is_alive ms (x-1,y))
  12.                              else false;
  13.  
  14. fun live_neighbours mat (r,c) =
  15. let
  16.     val arr = [(~1,~1),(~1,0),(~1,1),(0,~1),(0,1),(1,~1),(1,0),(1,1)]
  17.     fun add_to_index xs (r,c) = map (fn (a,b) => (a+r,b+c)) xs
  18.     fun is_alive_aux mat (r,c) = if(is_alive mat (r,c)) then 1 else 0
  19.     fun live_neighbours_aux mat (r,c) = map(is_alive_aux mat)(add_to_index arr (r,c))
  20.     fun sum lst = foldl op+ 0 lst;
  21. in
  22.     if(valid_index mat (r,c)) then sum(live_neighbours_aux mat (r,c)) else ~1
  23. end;
  24.  
  25. fun rule mat false i j = live_neighbours mat (i,j) = 3
  26.     | rule mat true i j = (live_neighbours mat (i,j)) = 3 orelse (live_neighbours mat (i,j)) = 2;
  27.    
  28. fun next_state_aux [] _ _= []
  29.     | next_state_aux mat i j = if (valid_index mat (i,j)) then
  30.       (rule mat (hd(List.drop(hd(List.drop(mat,i)),j))) i j)::(next_state_aux mat i (j + 1))
  31.       else [];
  32.      
  33. fun next_state [] _ = []
  34.     | next_state mat i= if (valid_index mat (i,0)) then (next_state_aux mat i 0) :: (next_state mat (i+1)) else [];
  35.    
  36. fun start_game mat 0 = mat
  37.     | start_game mat i = start_game (next_state mat 0) (i-1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement