fork(1) download
  1. import Data.List (permutations)
  2.  
  3. magicSquare = head . filter condition . map setTri . permutations . map (2^) $ [0..8]
  4. where
  5. setTri [] = []
  6. setTri (a:b:c:xs) = [[a, b, c]] ++ setTri xs
  7.  
  8. condition xs = line xs && row xs && diagonal xs
  9. where
  10. line (x:[]) = True
  11. line (x:xs) = (product x) == (product . head $ xs) && (line xs)
  12.  
  13. row ((x:[]):(y:[]):(z:[]):_) = True
  14. row (x:y:z:_) = (product . map head $ [x, y, z]) == (product . map middle $ [x, y, z]) && (row . map tail $ [x, y, z])
  15.  
  16. diagonal (a:b:c:_) = product [head a, middle b, last c] == product [last a, middle b, head c]
  17.  
  18. middle = head . tail
  19.  
  20.  
  21. main = mapM_ print magicSquare
Success #stdin #stdout 0.04s 6768KB
stdin
Standard input is empty
stdout
[2,256,8]
[64,16,4]
[32,1,128]