loading...

re: Writing a Tictactoe game in Haskell VIEW POST

FULL DISCUSSION
 

Very nice article, just two small tips:

  1. There is not really any reason to write a custom Eq instance ever, just derive it
  2. You could shorten your last function a bit with list comprehensions:
isThereAWinner move board = or . fmap (all check) $ idxs
  where check x = board !! x == Occupied move
        idxs = rows <> colums <> diagonals
        rows = [ [row * n + i | i <- [0..n - 1] ] | row <- [0..n - 1] ]
        columns = [ [col + i * n | i <- [0..n - 1] ] | col <- [0..n - 1] ]
        diagonals = [ [ ((i * j) `mod` n) + i * n | i <- [0..n - 1] ] | j <- [-1, 1] ]
        n = 3

this additionally scales easily to bigger boards by changing n

I am not completely sure if the code is correct as I hadnt had the chance to test it yet

 

Thanks Jan! That list comprehension is really readable. I’ll be sure to play with that and practice. Coming from a largely-JS/Ruby background, list comprehensions are definitely something I have to further internalize.

Thanks for noting the Eq derivation as well. Actually after writing this, I re-read that chapter of Learn You A Haskell and realized the same. I’ll update my source and leave an edit in this article.

code of conduct - report abuse