I have been impressed by many of the Mathematica functions I see, they seem to be very short, elegant, and they do so much with little amount of code.
Today I was looking at this interesting function in Mathematica help pages called DiagonalQ, which checks if a matrix is diagonal or not. (i.e. if all the elements off the matrix diagonal are zero or not).
I found the function interesting, as it is only one line.
Coming from a procedural background, and learning functional programming, I would have wrote such a function as probably any procedural programmer would, which is to loop over all the elements of the matrix and check if there is a non-zeros off the diagonal, and once one is found, then to terminate the loop and return the result. I would first start checking for boundary conditions and check that the input is valid.
The procedural style requires the familiar 2 loops, one over the rows of the matrix, and one over the columns. So I quickly wrote a procedural style function to implement the same thing as DiagonalQ. This is easy to code of course, but it is interesting to see how much shorter the functional procedure is
This shows the functional procedure and my procedure implementation
The above example illustrates how powerful functional programming seems to be. It does however require more time to get accustomed to, but I think it is well worth learning. I am currently using Mathematica to help me learn this style of programming.
The original function DiagonalQ from the help pages is here HTML
Some examples using the function DiagonalQ to test it