lxndio

Untitled

Nov 14th, 2017
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import System.Random
  2.  
  3. data CellState  = Dead | Alive deriving (Eq)
  4. data Cell       = Cell CellState deriving (Eq)
  5. data Row        = Row [Cell]
  6. data Map        = Map [Row]
  7.  
  8. instance Show CellState where
  9.     show Dead   = "_"
  10.     show Alive  = "#"
  11.  
  12. instance Show Cell where
  13.     show (Cell cellState)   = show cellState
  14.  
  15. instance Show Row where
  16.     show (Row cells)        = unwords $ map show cells
  17.  
  18. instance Show Map where
  19.     show (Map rows)         = unlines $ map show rows
  20.  
  21. getElem :: Int -> [a] -> a
  22. getElem n xs
  23.     | n >= length xs    = xs!!(n - length xs)
  24.     | n < 0             = xs!!(length xs + n)
  25.     | otherwise         = xs!!n
  26.  
  27. getNeighbours :: Int -> Int -> [[Bool]] -> [Bool]
  28. getNeighbours x y xs = [ getElem (x-1) (getElem (y-1) xs), getElem x (getElem (y-1) xs)  , getElem (x+1) (getElem (y-1) xs)
  29.                        , getElem (x-1) (getElem y xs)                                    , getElem (x+1) (getElem y xs)
  30.                        , getElem (x-1) (getElem (y+1) xs), getElem x (getElem (y+1) xs)  , getElem (x+1) (getElem (y+1) xs) ]
  31.  
  32. countLivingNeighbours :: Int -> Int -> [[Bool]] -> Int
  33. countLivingNeighbours x y xs = length [x | x <- getNeighbours x y xs, x == True]
  34.  
  35. intToCellState :: Int -> CellState -- TODO probably change to Maybe CellState one day
  36. intToCellState n
  37.     | n == 0    = Dead
  38.     | n == 1    = Alive
  39.     | otherwise = Dead
  40.  
  41. returnFixedRow :: Row
  42. returnFixedRow = Row $ map Cell $ map intToCellState [1,0,1,0,1]
  43.  
  44. returnFixedMap :: Map
  45. returnFixedMap = Map $ replicate 5 returnFixedRow
Advertisement