John Conway's game of life in Haskell: Code Review
I have written a small code that simulates the Game of Life by John Conway. This is the code
import Control.Concurrent
import System.Random
import Control.Monad
data Cell = Alive  Dead deriving Eq
instance Show Cell where
show Alive = "X"
show Dead = "0"
toCells :: [Int] > [Cell]
toCells arr = (\ x > if x==1 then Alive else Dead) <$> arr
getValue :: [Cell] > Int > Int > Int > Int > Int
getValue state w h x y =
if x>=0 && x < w && y>=0 && y<h
then case state !! (y*w + x) of
Dead > 0
Alive > 1
else 0
countNeighbours :: [Cell] > Int > Int > Int > Int > Int
countNeighbours state w h x y = sum $ (uncurry $ getValue state w h) <$> [(x,y+1),(x,y1),(x+1,y+1),(x+1,y),(x+1,y1),(x1,y+1),(x1,y),(x1,y1)]
newCell :: [Cell] > Int > Int > Int > Int > Cell
newCell state w h x y =
if state !! (y*w + x) == Alive
then if countNeighbours state w h x y == 3  countNeighbours state w h x y == 2 then Alive else Dead
else
if countNeighbours state w h x y == 3 then Alive else Dead
clock :: [Cell] > Int > Int >Int > Int > [Cell]
clock state x y w h =
if x == w1
then if y == h1 then [newCell state w h x y] else [newCell state w h x y] ++ clock state 0 (y+1) w h
else [newCell state w h x y] ++ clock state (x+1) y w h
coolPrint :: [Cell] > Int > String
coolPrint [] w = ""
coolPrint arr w = (show $ take w arr) ++ "\n" ++ coolPrint (drop w arr) w
update state w h= do
threadDelay 1000000
putStr "\ESC[2J"
putStrLn $ coolPrint state w
update (clock state 0 0 w h) w h
input = replicateM 625 (randomRIO (0,1))
runGame = do
s < input
update (toCells s) 25 25
I have to admit, I am not very proud of it... Perhaps the update and clock functions could be implemented using the StateT monad, giving it a cleaner look. The cell data seems redundant and useless. What do you think? Any suggestion?
See also questions close to this topic

Logic Sequence in Haskell
I'm new in haskell and i found 2 logic sequence who i dont know how to solve It. Right below the two sequences to be solved.
1)[5,8,11,17,20,26,29,32,38,41]
2)[2,4,8,10,12,16,18,22,24,28,30]

Hiding typeclass instance declarations while importing in Haskell
I am trying to make a tictactoe game, and I decided to construct types for cells (elements of the board) and the board as follows:
data Cell = X  O deriving (Show, Eq) type Board = [[Maybe Cell]]
Here, Nothing represents an empty cell, (Just X) and (Just O) represent cells filled with X and O respectively.
I would like to define (Maybe Cell) as a monoid as follows:
instance Monoid (Maybe Cell) where mempty = Nothing mappend Nothing x = x mappend (Just x) _ = (Just x)
And Board as another monoid with
instance Monoid Board where mempty = [[Nothing, Nothing, Nothing] ,[Nothing, Nothing, Nothing] ,[Nothing, Nothing, Nothing]] mappend = zipWith (zipWith mappend)  where the righthandside mappend is the addition on (Maybe Cell)
I know I could implement this absolutely without monoids, but I'm trying to explore the field, and it's just a really neat way to write it.
The problem that I get is that a
Maybe
monoid instance is already defined inGHC.Base
as follows:instance Semigroup a => Monoid (Maybe a)
This has a very different definition than what I want, but it causes duplicate instance declarations, so I can't just ignore it.
What I'm trying to do is to hide the
Monoid
instance of(Maybe a)
fromGHC.Base
to avoid duplicate instances. I tried searching a lot for that, but couldn't really find a way to hide that. I can't hide all ofMonoid
or all ofSemigroup
, because I need their functions, but I need to hide this specific instance declaration. Could anyone help me with that?NOTE: I'm using FlexibleInstances.

How can I make this Haskell development environment in Nix?
I'm trying to make a Haskell development environment for a web project that just has the dependencies
hakyll
,blaze
, andclay
. Only, clay appears to fail to build, complaining thatSetup: Encountered missing dependencies: hspec >=2.2.0 && <2.6, hspecdiscover >=2.2.0 && <2.6
, and I can't seem to get past this.I tried running
cabal2nix . shell > shell.nix
on this cabal file:name: openeditions version: 0.1.0.0 buildtype: Simple cabalversion: >= 1.10 executable site mainis: site.hs builddepends: base == 4.* , blazehtml , clay , hakyll == 4.12.* ghcoptions: threaded defaultlanguage: Haskell2010
But I'm running into the missing dependencies problem. Any ideas?

Why scala @tailrec can't be used on Option.flatMap?
In scala, the following 2 functions serve exactly the same purpose:
@tailrec final def fn(str: String): Option[String] = { Option(str).filter(_.nonEmpty).flatMap { v => fn(v.drop(1)) } } @tailrec final def fn2(str: String): Option[String] = { Option(str).filter(_.nonEmpty) match { case None => None case Some(v) => fn2(v.drop(1)) } }
However @tailrec only works in second case, in the first case it will generate the following error:
Error: could not optimize @tailrec annotated method fn: it contains a recursive call not in tail position Option(str).filter(_.nonEmpty).flatMap { v =>
Why this error was given? And why these 2 codes generate different kinds JVM bytecode

What is the correct implementation of addToLeftPlayerPos
I'm trying to follow this paper on functional reactive programming but I'm stuck on the second example in section 4.2.
I got the first example with the reader transformer up and running:
module Main where import FRP.BearRiver import Control.Monad.Trans.MSF.Reader type Game = Ball type Ball = Int type GameEnv = ReaderT GameSettings data GameSettings = GameSettings { leftPlayerPos :: Int , rightPlayerPos :: Int } ballToRight :: Monad m => MSF (GameEnv m) () Ball ballToRight = count >>> arrM addToLeftPlayerPos where addToLeftPlayerPos = (\n > (n +) <$> asks leftPlayerPos) hitRight :: Monad m => MSF (GameEnv m) Ball Bool hitRight = arrM (\i > (i >=) <$> asks rightPlayerPos)
But with the next step I'm struggling. I can't figure out how to introduce a writer transformer correctly, as I don't get it even to compile:
module Main where import FRP.BearRiver import Control.Monad import Control.Monad.Trans.MSF.Reader import Control.Monad.Trans.MSF.Writer type Game = Ball type Ball = Int type GameEnv m = WriterT [String] (ReaderT GameSettings m) data GameSettings = GameSettings { leftPlayerPos :: Int , rightPlayerPos :: Int } ballToRight :: Monad m => MSF (GameEnv m) () Ball ballToRight = count >>> arrM addLeftPlayerPos >>> arrM checkHitR where addLeftPlayerPos = (\n > (n +) <$> asks leftPlayerPos) checkHitR n = do rp < asks rightPlayerPos when (rp > n) $ tell ["Ball is at " ++ (show n)]
Actually the line with the function call
addLeftPlayerPos
is the problematic one, as the functionarrM addLeftPlayerPos
isn't given in the paper and my version seems to lack theWriterT
type signature as the type aliastype GameEnv m ...
suggestsWhat could be the correct implementation of the
addLeftPlayerPos
function?Edit: The compiler error is:
Expected type: MSF (GameEnv m) () Ball Actual type: MSF (ReaderT GameSettings m1) () () • In the expression: count >>> arrM addToLeftPlayerPos >>> arrM checkHitR

Spark Data Pipelines & Monads
Recently I have come across examples of Scala MONADs being used for Data Pipelines and a site also where this is being applied.
I am wondering how many persons are programming in this way. MONADs seem hard to define.
I am interested in the advantages in real work situations. I see few questions on SO in this regard. Moreover, the Holden Karau et al experts make no mention of this in their excellent texts.
This may be too broad a question but it does relate to a programming style.

Operand ++ doesn't increment in my function sometimes
int generation = 0; System.out.println("\nGeneration " + generation + ":"); for(int i = 0; i < rowcol; i++) { if(i > 0) { System.out.println(); } for(int j = 0; j < rowcol; j++) { System.out.print(arr[i][j] + " "); } } boolean run = true; int copy[][] = arr; while(run) { int alive = 0; for(int i = 0; i < rowcol; i++) { for(int j = 0; j < rowcol; j++) { alive = 0; //top left if(i1 > 1 && j1 > 1) { if(arr[i1][j1] == 1) { ++alive; } } //top if(i1 > 1) { if(arr[i1][j] == 1) { ++alive; } } //top right wtf if(i1 > 1 && j+1 < rowcol) { if(arr[i1][j+1] == 1) { ++alive; } } //left if(j1 > 1) { if(arr[i][j1] == 1) { ++alive; } } //right if(j+1 < rowcol) { if(arr[i][j+1] == 1) { ++alive; } } // down left if(i+1 < rowcol && j1 > 1) { if(arr[i+1][j1] == 1) { ++alive; } } //down if(i+1 < rowcol) { if(arr[i+1][j] == 1) { ++alive; } } //down right if(i+1 < rowcol && j+1 < rowcol) { if(arr[i+1][j+1] == 1) { ++alive; } } if(arr[i][j] == 1) { if(alive < 2) { copy[i][j] = 0; } else if(alive > 3) { copy[i][j] = 0; } } else if(arr[i][j] == 0 && alive == 3) { copy[i][j] = 1; } } } arr = copy; generation++; System.out.println("\nGeneration " + generation + ":"); for(int i = 0; i < rowcol; i++) { if(i > 0) { System.out.println(); } for(int j = 0; j < rowcol; j++) { System.out.print(arr[i][j] + " "); } } } }
}
this is my code basically I have a homework project to make the Game of Life with 1s and 0s in a grid however big the user inputs but I'm having a problem when I'm checking for how many cells around it are alive
Enter number of rows/columns: 3
0,1,1,1,0,0,0,1,0
Generation 0:
0 1 1
1 0 0
0 1 0
Generation 1:
0 1 0
1 1 1
1 0 0
That is what I have in my console but there should only be three ones the middle top and the left and right in the middle row I was using the debugger and found out that when it goes to check my middle value in the middle row it does count the one in the top right as alive for some reason even though it passes through both of the if statements and I don't know why so the alive variable ends up being three for that spot in the middle of the middle row changing it to a one this code might be horrible btw I'm fairly new to this stuff. I hope I provided enough details as well just ask about anything else you need to know to help its greatly appreciated.

Multithreaded Conway's Game of Life in C++ occasionally hitching?
For practice I've implemented Conways' Game of Life in C++ with updates to the "world" being handled with parallel processing. I'm using SFML for graphics.
Adding multithreading definitely made it run faster (at least on this 4core machine) but I noticed it has issues. If I run it in a
Debug
configuration from Visual Studio 2017 it seems to start very slow, but after running for 2 seconds it suddenly gets faster and runs smoothly. But if I run it inRelease
configuration then it runs even faster thanDebug
did but every half a second or so it "hitches" or stutters and doesn't run smoothly like I expected.What could be causing these two behavior issues and how can I fix them?
GameOfLife.cpp:
#include "GameOfLife.h" #include <iostream> #include <vector> #include <math.h> #include <thread> #include <mutex> #include <SFML/Graphics.hpp> class GameOfLife { public: GameOfLife(int sizeX, int sizeY); uint8_t & getCell(int x, int y); sf::Vector2i get2D(int i); void doUpdate(int start, int end); virtual ~GameOfLife() = default; void update(); std::vector<sf::Vector2i> getLiveCells(); private: std::vector<uint8_t> world; }; std::mutex updateListLock; std::vector<sf::Vector2i> pendingUpdates; sf::Vector2i worldSize; GameOfLife::GameOfLife(int sizeX, int sizeY) { worldSize = sf::Vector2i(sizeX, sizeY); // initialize world to specified size, all starting as dead world = std::vector<uint8_t>(sizeX * sizeY, 0); // reserve space for worst case (every cell needs to be updated) pendingUpdates.reserve(sizeX * sizeY); // place a glider getCell(1, 3) = true; getCell(2, 4) = true; getCell(3, 2) = true; getCell(3, 3) = true; getCell(3, 4) = true; // place a glider at topcenter int midX = std::floor(worldSize.x / 2); getCell(midX + 1, 3) = true; getCell(midX + 2, 4) = true; getCell(midX + 3, 2) = true; getCell(midX + 3, 3) = true; getCell(midX + 3, 4) = true; } uint8_t& GameOfLife::getCell(int x, int y) { return world[y * worldSize.x + x]; } sf::Vector2i GameOfLife::get2D(int index) { int y = std::floor(index / worldSize.x); int x = index % worldSize.x; return sf::Vector2i(x, y); } // Update the cells from position start (inclusive) to position end (exclusive). void GameOfLife::doUpdate(int start, int end) { for (int i = start; i < end; i++) { auto pos = get2D(i); // # of alive neighbors int aliveCount = 0; // check all 8 surrounding neighbors for (int nX = 1; nX <= 1; nX++) // nX = 1, 0, 1 { for (int nY = 1; nY <= 1; nY++) // nY = 1, 0, 1 { // make sure to skip the current cell! if (nX == 0 && nY == 0) continue; // wrap around to other side if neighbor would be outside world int newX = (nX + pos.x + worldSize.x) % worldSize.x; int newY = (nY + pos.y + worldSize.y) % worldSize.y; aliveCount += getCell(newX, newY); } } // Evaluate game rules on current cell switch (world[i]) // is current cell alive? { case true: if (aliveCount < 2  aliveCount > 3) { std::lock_guard<std::mutex> lock(updateListLock); pendingUpdates.push_back(pos); // this cell will be toggled to dead } break; case false: if (aliveCount == 3) { std::lock_guard<std::mutex> lock(updateListLock); pendingUpdates.push_back(pos); // this cell will be toggled to alive } break; } } } void GameOfLife::update() { unsigned maxThreads = std::thread::hardware_concurrency(); // divide the grid into horizontal slices int chunkSize = (worldSize.x * worldSize.y) / maxThreads; // split the work into threads std::vector<std::thread> threads; for (int i = 0; i < maxThreads; i++) { int start = i * chunkSize; int end; if (i == maxThreads  1) // if this is the last thread, endPos will be set to cover remaining "height" end = worldSize.x * worldSize.y; else end = (i + 1) * chunkSize; std::thread t([this, start, end] { this>doUpdate(start, end); }); threads.push_back(std::move(t)); } for (std::thread & t : threads) { if (t.joinable()) t.join(); } // apply updates to cell states for each (auto loc in pendingUpdates) { // toggle the dead/alive state of every cell with a pending update getCell(loc.x, loc.y) = !getCell(loc.x, loc.y); } // clear updates pendingUpdates.clear(); } std::vector<sf::Vector2i> GameOfLife::getLiveCells() { std::vector<sf::Vector2i> liveCells; liveCells.reserve(worldSize.x * worldSize.y); // reserve space for worst case (every cell is alive) for (int i = 0; i < worldSize.x * worldSize.y; i++) { auto pos = get2D(i); if (world[i]) liveCells.push_back(sf::Vector2i(pos.x, pos.y)); } return liveCells; }

Speeding up tkinter canvas edits using itemconfig?
In a quest to recreate Conway's Game of Life, I decided to try to use Tkinter for the first time. I originally built the program, then realized it was far too slow to update every element in an NxN grid. I optimized it so that would not be necessary, to where it only checks the elements surrounding "alive" cells. This intuitively would mean that it would run at around the same speed for any value of N, but it is far from that. I have narrowed my problem down to the use of canvas.itemconfig(). The timing of my program goes from 0.2 seconds to over 11 seconds with its use.
I was wondering if there is a faster way to implement itemconfig, or something similar.
Without the itemconfigs and with just canvas.update(), the program takes about 2 seconds to do 100 iterations with the current settings.
Please reply if I need to include any more information, this is only my second time asking a question on SO so I hope I covered everything.
Code:`
from tkinter import * import numpy as np import time # Main code is at the bottom master = Tk() boxNumberEnter = 200; boxNumber = boxNumberEnter; size = 1000; boxSize = size/boxNumber; n = int(boxNumberEnter/2); aliveList = [] aliveList2 = [] grid = np.zeros((boxNumber,boxNumber)).astype('int') grid[n][n] = 1 grid[n][n1] = 1 grid[n][n2] = 1 grid[n][n3] = 1 grid[n][n4] = 1 grid[n+4][n] = 1 grid[n+4][n1] = 1 grid[n+4][n2] = 1 grid[n+4][n3] = 1 grid[n+4][n4] = 1 grid[n+2][n4] = 1 grid[n+2][n] = 1 w = Canvas(master, width=size, height=size) w.pack() for box in range(0,boxNumber): w.create_text((box*boxSizeboxSize/2)+boxSize, 20, text=str(box1)) for box in range(0, boxNumber): w.create_text(20, (box * boxSize  boxSize / 2) + boxSize, text=str(box1)) def create_rec(s, x, y): w.create_rectangle((x + 1) * boxSize, (y + 1) * boxSize, (x + 1) * boxSize + boxSize, (y + 1) * boxSize + boxSize, fill=s, tags=(str(x) + "" + str(y))) num = 0 # The meat of it starts here for i in range(0, boxNumber): for j in range(0, boxNumber): if grid[i][j] == 1: aliveList.append([i, j]) create_rec("grey", i, j) else: create_rec("white", i, j) master.update() newGrid = np.zeros((boxNumber, boxNumber)).astype('int') count = 0 frameCount = 0; t = time.time() while True: frameCount+=1 count+=1 if count==100: break for b in aliveList: for i in range(b[0]1, b[0]+2): for j in range(b[1]  1, b[1] + 2): num1 = 0 if(i+1 < boxNumber and i1 > 0 and j+1 < boxNumber and j1 > 0): num1 = grid[i + 1][j] + grid[i  1][j] + grid[i + 1][j + 1] + grid[i  1][j + 1] + grid[i  1][j  1] + \ grid[i][j  1] + grid[i][j + 1] + grid[i + 1][j  1] if num1 == 2: if(grid[i][j]==1): if [i, j] not in aliveList2: aliveList2.append([i, j]) if num1 == 3: if [i, j] not in aliveList2: aliveList2.append([i, j]) for b in aliveList: grid[b[0]][b[1]] = 0; if (frameCount >= 0): w.itemconfig(str(b[0]) + "" + str(b[1]), fill="white") aliveList = aliveList2.copy() for b in aliveList: grid[b[0]][b[1]] = 1; if (frameCount >= 10): w.itemconfig(str(b[0]) + "" + str(b[1]), fill="grey") aliveList2.clear() #grid = newGrid master.update() #if(frameCount>=10): # master.update() # frameCount = 0; print(time.time()t) `
Thanks in advance!