< Back

Lecture 29 - Day 2 of Haskell


Activity

Write a function magic_square :: [[Int]] -> Bool, which takes a 2-dimensional (Square!) list, and returns True if the parameter is a magic square. For simplicity sakes, we will assume a square is magic if all of the rows, and all of the columns sum to the same value.

To make writing this function easier, define functions sum_column :: [[Int]] -> Int -> Int, and sum_row :: [[Int]] -> Int -> Int. Both of these functions take "2" parameters (using curring). They take a 2-dimensional (again, Square!) list of Integers, and an Integer index. It they should return the sum of the elements along the specified column and row, respectively.

You may need to define more helper functions! I personally wrote at least 4 more functions, but you could easily reduce that. It may result in some uglier looking code, but it is doable!

Time permitting, add in a clause to check the diagonals as well. In a real magic square, the diagonals should sum to the same values as the rows and columns! If you're really bored, you could also write a prolog program to generate such magic squares!