June 1, 2007

A different kind of love…

Posted in Life, Mathematics at 11:25 am by pmatos


The song A Finite Simple Group Of Order Two with lyrics,

The path of love is never smooth
But mine’s continuous for you
You’re the upper bound in the chains of my heart
You’re my Axiom of Choice, you know it’s true

But lately our relation’s not so well-defined
And I just can’t function without you
I’ll prove my proposition and I’m sure you’ll find
We’re a finite simple group of order two

I’m losing my identity
I’m getting tensor every day
And without loss of generality
I will assume that you feel the same way

Since every time I see you, you just quotient out
The faithful image that I map into
But when we’re one-to-one you’ll see what I’m about
‘Cause we’re a finite simple group of order two

Our equivalence was stable,
A principal love bundle sitting deep inside
But then you drove a wedge between our two-forms
Now everything is so complexified

When we first met, we simply connected
My heart was open but too dense
Our system was already directed
To have a finite limit, in some sense

I’m living in the kernel of a rank-one map
From my domain, its image looks so blue,
‘Cause all I see are zeroes, it’s a cruel trap
But we’re a finite simple group of order two

I’m not the smoothest operator in my class,
But we’re a mirror pair, me and you,
So let’s apply forgetful functors to the past
And be a finite simple group, a finite simple group,
Let’s be a finite simple group of order two
(Oughter: “Why not three?”)

I’ve proved my proposition now, as you can see,
So let’s both be associative and free
And by corollary, this shows you and I to be
Purely inseparable. Q. E. D.

August 5, 2006

Bee Season

Posted in Mathematics, Movies at 9:01 pm by pmatos

Bee Season

Plot Outline:A wife and mother begins a downward emotional spiral, as her husband avoids their collapsing marriage by immersing himself in his 11 year-old daughter’s quest to become a spelling bee champion.

Personal Comments:

Richard Gere is definitely one of my favourite actors since An Officer and a Gentleman. “Ah, that’s a Great Movie!”

Anyway, I got this movie from 2005, and thought to myself “How strange is that I didn’t catch it up on the cinema?”. Anyway, I got a little bit disappointed. Not directly with Richard Gere performance which was great as always but with the movie itself. The Bee competition is, IMO, an excellent opportunity for teenagers to participate in an intellectual competition (more about the Spelling Bee in the end of the post) and the movie is centered on it, however, there’s also a heavy religious component on the movie which was a bit too much. At the end, I just asked myself: “Why was the religious component important in the movie at all?” I can assess some logic to it like Aaron changing religion, etc, but no logic at all in Eliza trying to talk with God.

Still, the movie is good apart from the religious components and the sadness component in most of the movie. If you need a recent ‘cheer-up’ movie for an afternoon or evening, I would advise you to get, also from Richard Gere, Shall we Dance.

For those who not know what the Bee is about, the Spelling Bee is a very well-known competition in the states where people try to spell some words in order to win a competition. Although it seems easy, words get increasingly difficult, to the point where some words are really hard and you can only derive their spelling by knowing its roots. The official site can be found here.

The only variation I know on the Bee is the MIT Integration Bee, where off course, instead of having to spell a given word, you have to solve a given integral… and you have 4 minutes per integral. Well, it’s very, very, very nice to see students excited by solving integrals. The competition seems extremely interesting and it’s really unfortunate that it seems unique in the world.
You can find some examples of integrals from the MIT Integration Bee here.

June 14, 2006

The Chain Rule… inside out!

Posted in Mathematics at 11:39 am by pmatos

The Chain Rule is definitely an extremely useful tool, whether you’re working in single-variable calculus or multi-variable calculus. Since I had some fun with it today I’ll give a brief explanation here today… hopefully I’ll help someone in the future!

Chain Rule for single-variable functions ([tex]f : \mathbb{R} \rightarrow \mathbb{R}[/tex])

This is the simplest case and in fact to understand the rule for the general case you should start here.

Basically consider [tex]g = f(r(t))[/tex], so we simply have [tex]g'(t) = f'(r(t)) \cdot r'(t)[/tex].
As an example, consider:
[tex]f(x) = 1/x[/tex] and,
[tex]r(t) = t^2, t \neq 0 [/tex].
So if we wish to compute the derivative of [tex]g(t) = f(r(t))[/tex], we just need to apply the chain rule above:
[tex]g'(t) = f'(r(t)) \cdot r'(t) = [/tex]
[tex] = f'(t^2) \cdot 2t = [/tex]
[tex] = -1/(t^2) \cdot 2t = \frac{-2t}{t^2} = \frac{-2}{t} [/tex]

I left the obvious part unmentioned (the why I had to restrict [tex]r[/tex]). Since, [tex]D_f = ]-\infty, 0[ \cup ]0, +\infty[ [/tex] and [tex]D^’_g = \mathbb{R}[/tex], this is only valid if we restrict [tex]r[/tex].

Now, onto a more general case.

Chain Rule for multi-variable functions ([tex]f : \mathbb{R}^n \rightarrow \mathbb{R}[/tex])

So, given a scalar field defined on an open set [tex]S[/tex] in [tex]\mathbb{R}^n[/tex], and let [tex]r[/tex] be a vector-valued function which maps an interval J from [tex]\mathbb{R}^1[/tex] into [tex]S[/tex]. Define the composite function [tex]g = f \circ r[/tex] on [tex]J[/tex] by the equation:
[tex]g(t) = f[r(t)][/tex] if [tex]t \in J[/tex]

Let [tex]t[/tex] be a point in [tex]J[/tex] at which [tex]r'(t)[/tex] exists and assume that [tex]f[/tex] is differenciable at [tex]r(t)[/tex]. Then [tex]g'(t)[/tex] exists and is equal to the dot product:
[tex]g'(t) = \nabla f(a) \cdot r'(t)[/tex], where [tex]a = r(t)[/tex]

Note that [tex]\nabla f(a)[/tex] known as the gradient of [tex]f[/tex] at [tex]a[/tex] is the vector whose components are the partial derivatives of [tex]f[/tex] at [tex]a[/tex]:
[tex]\nabla f(a) = (D_1 f(a), \ldots, D_n f(a))[/tex]

So, [tex]\nabla f(a)[/tex] is a vector field defined at each point [tex]a[/tex] where the partial derivatives [tex]D_1 f(a), \ldots, D_n f(a)[/tex] exist.

Consider that [tex]F = f \circ r[/tex] and as we have been considering in this section [tex]f : \mathbb{R}^2 \rightarrow \mathbb{R}[/tex] and [tex]r : \mathbb{R} \rightarrow \mathbb{R}^2[/tex], so we have that [tex]F : \mathbb{R} \rightarrow \mathbb{R}[/tex]. They are given by [tex]f(x, y) = x^2 + y^2, r(t) = (t, t^2)[/tex] and let’s compute [tex]F'(t), F”(t)[/tex].

By using the chain rule we have: [tex]F'(t) = \nabla f(r(t)) \cdot r'(t)[/tex]. So,
[tex]\nabla f = \left(\frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}\right) = (2x, 2y)[/tex] and
[tex]r'(t) = (1, t^2)[/tex]

Substituting in the chain rule:
[tex]F'(t) = \nabla f(r(t)) \cdot r'(t) = [/tex]
[tex] = (2t, 2t^2) \cdot (1, 2t) = [/tex]
[tex] = 2t + 4t^3 [/tex]

And trivially, we need no chain rule for the second derivative: [tex]F”(t) = [F'(t)]’ = 12t^2+2 [/tex].

In general, the chain rule for multi-variable vector fields ([tex]f : \mathbb{R}^n \rightarrow \mathbb{R}^m[/tex])

Now, let’s look at the general case when we have vector fields.
Chain Rule: Let [tex]f[/tex], and [tex]g[/tex] be vector fields such that the composition [tex]h = f \circ g[/tex] is defined in a neighborhood of a point [tex]a[/tex]. Assume that [tex]g[/tex] is differentiable at [tex]a[/tex], with total derivative [tex]g'(a)[/tex]. Let [tex]b = g(a)[/tex] and assume that [tex]f[/tex] is differentiable at [tex]b[/tex], with total derivative [tex]f'(b)[/tex]. Then [tex]h[/tex] is differentiable at [tex]a[/tex], and the total derivative [tex]h'(a)[/tex] is given by:
[tex]h'(a) = f'(b) \circ g'(a)[/tex],
the composition of the linear transformations [tex]f'(b)[/tex] and [tex]g'(a)[/tex].

Note that the derivatives of vector fields are given by their respective jacobian matrices and that the composition of the linear transformation is obtained by the multiplication of the jacobian matrices (which represent the linear transformations).

Ok, so let’s try to do a complete exercise (since officially, or from a theoretical point-of-view, we already know how to do it).
[tex]f: \mathbb{R}^2 \rightarrow \mathbb{R}^2[/tex]
[tex]f(x, y) = (e^{x+2y}, \sin(y+2x))[/tex]
[tex]g: \mathbb{R}^3 \rightarrow \mathbb{R}^2[/tex]
[tex]g(u,v,w) = (u + 2v^2 + 3w^3, 2v-u^2)[/tex]

Let’s compute the jacobian matrices of [tex]f[/tex] and [tex]g[/tex]:
[tex]D_f = \begin{pmatrix} \frac{\partial f_1}{\partial x} & \frac{\partial f_1}{\partial y} \\ \frac{\partial f_2}{\partial x} & \frac{\partial f_2}{\partial y} \end{pmatrix} = [/tex]
[tex] = \begin{pmatrix} e^{x+2y} & 2e^{x+2y} \\ 2\cos(y+2x) & \cos(y+2x) \end{pmatrix}[/tex]

[tex]D_g = \begin{pmatrix}\frac{\partial g_1}{\partial u} & \frac{\partial g_1}{\partial v} & \frac{\partial g_1}{\partial w}\\ \frac{\partial g_2}{\partial u} & \frac{\partial g_2}{\partial v} & \frac{\partial g_2}{\partial w}\end{pmatrix} = [/tex]
[tex] = \begin{pmatrix}1 & 4v & 9w^2 \\ -2u & 2 & 0 \end{pmatrix}[/tex]

Now, define [tex]h(u,v,w) = f(g(u,v,w))[/tex] and compute [tex]D_h(1,-1,1)[/tex]. Well, well… here’s the application of our chain rule. So, by the chain rule:
[tex]h(1,-1,1) = f'(g(1,-1,1)) \circ g'(1,-1,1)[/tex]

By substitution in the expression:
[tex]g(1,-1,1) = (1+2+3, -2-1) = (6,-3)[/tex]

By substituting in the jacobian matrix computed previously for [tex]f[/tex] the value of [tex]g(1,-1,1)[/tex]:
[tex]f'(g(1,-1,1)) = f'(6,3) = \begin{pmatrix} 1 & 2 \\ 2\cos(9) & \cos(9) \end{pmatrix}[/tex]

By substituting in the jacobian matrix computed previously for [tex]g[/tex]:
[tex]g'(1,-1,1) = \begin{pmatrix} 1 & -4 & 9 \\ -2 & 2 & 0 \end{pmatrix}[/tex]

Now that we have computed all the values needed for the chain rule application, applying it is just composing the linear transformations given by the derivatives of [tex]f[/tex] and [tex]g[/tex], which is another way of saying that we need to multiply their jacobian matrices:
[tex]h'(1,-1,1) = \begin{pmatrix} 1 & 2 \\ 2\cos(9) & \cos(9) \end{pmatrix} \cdot \begin{pmatrix} 1 & -4 & 9 \\ -2 & 2 & 0 \end{pmatrix} = [/tex]
[tex] = \begin{pmatrix}-3 & 0 & 9 \\ 0 & -6\cos(9) & 18\cos(9) \end{pmatrix}[/tex]

And we’re done… :-)
Computing Jacobian’s and working with these kinds of tools are extremelly helpful in Geometry, Differential Calculus and some branches of Physics.


  • Weisstein, Eric W. “Chain Rule.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/ChainRule.html
  • Apostol, Tom “Calculus”, Volume II, Second Edition
  • Anton, Bivens and Davis, Calculus, Seventh Edition

May 30, 2006

ANN: A Matemática das Coisas

Posted in Mathematics, Portuguese at 4:46 pm by pmatos

A Matemática das Coisas é o tema de mais um colóquio no Pav. do Conhecimento:

Será verdade que o amor é cego? Para a matemática, a resposta é um redondo “Não!”. Genes, cheiros, classe social e cor da pele são factores fundamentais para a escolha do parceiro em todo o reino animal, mesmo entre os seres humanos. A forma como é feita essa escolha é o tema do próximo colóquio do ciclo “A Matemática das Coisas”, que terá lugar no sábado, dia 3 de Junho, às 15h, no auditório do Pavilhão do Conhecimento – Ciência Viva.

O matemático Fabio Chalub (Universidade Nova de Lisboa) e a socióloga Cristina Palma Conceição (Instituto Superior de Ciências do Trabalho e da Empresa) falarão sobre as contribuições da Teoria de Jogos para construir um modelo sobre o comportamento animal na escolha do parceiro sexual. Discutirão a relação entre o comportamento de um lagarto e o jogo infantil “Pedra-Tesoura-Papel” e mostrarão como os conflitos entre o macho e a fêmea se transferem para o nível genético. Com base nas estatísticas de casamento em Portugal, abordarão a prevalência de uniões entre indivíduos com afinidades de classe social e mostrarão que a matemática também pode prever o comportamento humano.

A entrada para o colóquio é gratuita e oferece a oportunidade de visitar também as exposições do Pavilhão do Conhecimento – Ciência Viva. Poderá haver tradução simultânea em Língua Gestual Portuguesa, após marcação.

Ainda a propósito do tema deste colóquio, o Pavilhão do Conhecimento – Ciência Viva convida os visitantes a participarem em várias actividades que relacionam a biologia com a matemática. Jogos sobre hereditariedade, avaliar se o próprio rosto seria mais bonito se tivesse uma simetria perfeita e conhecer o Jogo da Vida inventado pelo matemático J. Horton Conway, são algumas das propostas. Estes ateliers têm lugar entre os dias 27 de Maio e 10 de Junho, durante o horário de abertura do Pavilhão.

April 26, 2006

Do not mess with the primes…

Posted in Mathematics at 11:08 am by pmatos

Hummmf, I love prime numbers… They are special, they are wierd, they are… well, prime! For those living in a galaxy far, far away…
A prime number is basically a number with only two divisors 1 and itself. By definition 1 is not prime.

So, we have 2, 3, 5, 7, 9… ahah, nope… 9 is not prime… 11, 13…
Still, I got mad today… someone made up a definition which make primes… deficient!!! For me, primes should by definition be not deficient. Oh well… nothing can be done anyways!

Oh, by the way, for those of you with some free time give a try at the current Al Zimmermanns contest, very nice! In fact, when I saw the contest it seemed rather obvious at first but that is not so… First thing I though was obviously interpolation but interpolation does not solve the problem at all. So, you can ‘search’, well, search is nice, and the only way… Search heuristics are however a different matter and the contest is all about that!

I also love Pi but I’ll leave that for another post…

March 21, 2006

Mathematical Telepaty

Posted in Computers, Mathematics at 12:26 pm by pmatos

My girlfriend sent me the other day the following link: http://kardini.fateback.com/telepatiav.htm

The play is nice but as usual nothing more than a trick with basic number theory (and as it is normal, with the number 9).
The instructions are as follows:

  • Choose a number with two digits, let’s call it z. z is composed of the two digits x and y and is given by:
    [tex]z = 10x – y[/tex]
  • Now, subtract from z both digits and you’ll obtain the final number, f.
    [tex]f = z – x -y[/tex]
  • The next step is to search the table for f and it’ll guess which symbol associated with it.

The trick is now very obvious since [tex]f = z -x -y = 10x – x -y = 9x[/tex]. Basically all multiples of 9 are associated with the same symbol, which will be the symbol given as the guess (which will always be correct, by the way). All the other symbols are randomly chosen.

Well, this is not new. 9 has several nice properties but none are used in this trick. For example, it could say to subtract from z, two times the first digit and one time the second and f would be a multiple of 8. You would just have to put the same symbol in every multiple of 8. But 9 is nice for tricks? Why? Because the sum of the digits of a two-digit multiple of 9 is 9. I’ve read about some tricks which used this property. I can’t remember any but I can make up one. Imagine an integer between 10 and 99 (inclusive). Multiply by 4, sum all its digits, subtract 1, multiply by 8, sum all its digits, if the number is less than 10 sum all its digits again until you have a 1-digit number. Now, multiply by nine. Sum its digits, and take 4. I’ll guess the number you have is 5! And it will always be… all the mambo-jambo I just invented tricked your mind into thinking you’re doing something useful when it was plain useless. The kernel of the operation is the multiplication by 9 and the sum of its digits. You sum them and you’ll get 9 (I know that!) and then I ask you to take 4 and I’ll guess 5 which will be correct. You’ll be thinking I’m a magic and I only know the basic property of multiples of 9. :)

Have fun!

February 23, 2006

Mathemagical Meetings

Posted in Mathemagical Meetings, Mathematics at 11:14 am by pmatos

Being my girlfriend an avid student of Mathematics, with a strong and sexy inclination to Algebra and Analysis we both usually spend several hours talking about various subjects. From abelian monoids, groups, rings, hermitian matrices properties, semi-definiteness, other algebra and analysis niceties to algorithms like FourierMotzkin, Barvinok, OmegaTest, etc.

Lately we’ve even scheduled these meetings where we both meet to talk about Mathematics. These are appointed to every Saturday’s early in the morning. So, we have decided some things are terribly nice and ingenious for a wide audience. Things people cannot even imagine how nice it is… surprising results, beautiful theorems… so I will open a new series on this blog: “Mathemagical Meetings”

Hopefully every week you’ll have a summary with the nicest mathematics and computation we talked about that morning.

See you saturday then…

February 22, 2006

Palestra: Sudoku, futebol, diplomacia e outros aspectos da matemática

Posted in Education, Mathematics, Portuguese at 9:13 pm by pmatos

O Prof. Jorge Buescu do Departamento de Matemática do Instituto Superior Técnico dará amanhã uma palestra na Faculdade de Ciências da Universidade de Lisboa integrada no 4º Ciclo de Palestras “Matemática, Ciência e Arte”, 2005/2006.

Como devem saber o Prof. Buescu tem uma excelente reputação a nível nacional e internacional, publicou alguns livros na área da divulgação científica, algo em que é exímio. Assim, não convém perder estas oportunidades. Já assisti a várias palestras e nunca saí de lá como se tivesse perdido o meu tempo.

E claro, a parte interessante é que aqueles que não podem ou não têm tempo para se deslocar ao local da palestra podem assistir á mesma, em directo, confortavelmente do vosso emprego/casa pois vai ser transmitida em directo a partir da internet.

January 2, 2006

And give me 43…

Posted in Mathematics at 10:41 am by pmatos

230,402,457 - 1 = 31541647561884608093...11134297411652943871

is the most recent Mersenne prime. The Mersenne-43!

December 9, 2005

Teaching Mathematica as First Programming Language…

Posted in Computers, Education, Lisp, Mathematics, Programming, Scheme, Uncategorized at 1:57 pm by pmatos

is worse than shooting yourself in the foot… worse than shooting yourself in the head… is like shooting a whole bunch of students in the head, his friends, parents and colleagues. I would better call it a genocide.
From the wikipedia definition of genocide:

Genocide is (…) Killing members of the group; Causing serious bodily or mental harm to members of the group; Deliberately inflicting on the group conditions of life calculated to bring about its physical destruction in whole or in part; Imposing measures intended to prevent births within the group; and forcibly transferring children of the group to another group (…)

Students learning Mathematica as a first programming language are most probably mentally mutilated beyond hope of regeneration. In what follows I will explain why this is so.

During my degree in Software and Computer Engineering I had the possibility to learn programming in various languages like C, C++, JAVA, and some more eccentric languages like Scheme, Common Lisp and Mathematica. During the last years teaching Programming Fundamentals in Scheme as a first Programming Language in Software and Computer Engineering and following students from the Mathematics Department which learn Mathematica as a first Programming Language I’ve noticed the following differences:

  • Mathematica does not ease teaching students Programming Techniques, while Scheme does.
  • Mathematica makes it hard to teach good programming styles while the PLT Scheme approach makes it much easier.
  • Mathematica makes the learning of abstract datatypes (ADTs) extremelly difficult, while Scheme mostly enforces it.
  • Mathematica makes it even more awkard the teaching of orders of growth while Scheme does not.
  • Usual Programming Concepts like Interpreter, Compiler, REPL are not easily taught to students using Mathematics. PLT Scheme makes them explicit.

Now, I’ll try to detail each of the previous items in more detail.

Programming Styles

A beginning programmer needs, more than usual, that tools work on his side. No need for highly extensible, general-purpose, do-all tool (that’s why in general everyone works in windows, and why no beginner starts programming in emacs). If they are learning a programming language they already have a steep curve to go through, no need for another one to learn about an editor or how pretty-print stuff, indent or anything else.

Mathematica interface goes against these principles. Its interface is highly problematic, counter-intuitive and ugly. No help source colouring is provided and paren-matching functions are as simple as they can be. Check the snapshot!

  • It’s hard to keep track of what each parentheses close;
  • No colouring at all;
  • No support for indentation – the code is indented automatticly but if you for some reason miss the indentation and destroy the automatic indentation (remember, they are only beginners) it’s hard to get it back in place;
  • Copy-pasting the code can get a harsh job due to newline problems, etc… (I was never able to understand these issues)

Now, for your delight, check for example a PLT Scheme snapshot.


One thing which is particularly annoying in Mathematica is its uses of lists. Students learning Mathematica know surely all of the following functions for lists: PreppendTo, Preppend, Append, AppendTo, Length, First, Rest and [[_]].

Lists are a very good datatype but one that should be used with care not to shoot yourself in the foot. The major problem is Lists in Mathematica are not Lists. Lists in Mathematica are vectors, uni-dimensional tensors, and what makes things more irritating is that they are called lists. Check the following copy-pasted from Mathematica 5.1 help on List:

- {e1, e2, ...} is a list of elements.
- {a, b, c} represents a vector.
- {{a, b}, {c, d}} represents a matrix.
- Nested lists can be used to represent tensors.

Geeez, check the first line, oh it’s a list of elements… some lines below… it’s a vector… 2 lines below, oh no, nested lists…

This will not make sense of any student and imagine what a beginning student will learn from this? Lists and vectors are probably the same. Which is utterly incorrect!

From the Dictionary of Algorithms and Data Structures on list:

Definition: A collection of items accessible one after another beginning at the head and ending at the tail.

And on vector (also known as 1D-array):

Definition: A set of items which are randomly accessible by numeric index.

So, definitely this is a vector. How we really know the Mathematica list is a vector and not a list? Check next section on orders of growth.

This seems like a stupid non-sense that any student may go through without any problem but it is not true. Mathematica students learn talk about lists and which is ultimately worse, “think” about lists when they really mean vectors. And these are basic ADTs, every other ADT knowledge will come distorted because of this.

One can think:

Oh, no big deal, I can explain my students that lists and vectors are one. There are list functions and vector functions that work exactly on the same datatype (which is true).

You can explain this fact and probably 40% (at best) of them will understand but this will not help. When they get to learn other programming languages like C++ (which have separate STL List and Vector), Common Lisp, Scheme, etc, etc, etc… they won’t understand.
Using Mathematica and getting used to the fact that lists and vectors are the same will make them bad programmers for the rest of their days and will mutilate them and everyone who this person might teach.

Orders of Growth

Although we do not teach our students much about orders of growth in a first programming languages course, we do mention about the computational cost of some function and the computational cost of each ADT we use. However, we do know most students in their first project are eager to make them as computationally efficient as possible so that it’ll run faster than of most of their colleagues, not knowing that:

Premature Optimization is the Root of all Evil!
— Donald E. Knuth

Imagine that a student A is asked to define a function in Scheme that given an ordered list of numbers and a number (which is known to be in the list) should return the position (1-based) of the element in the list. A smart student will try to make is run as fast as hell so it uses a neat trick:

  ;; Returns the position of a given element in an ordered list.
  ;; (give-element '(2 3 6 8 15) 8) => 4
  (define (give-element-fast l n)
    (define (aux l i)
      (let* ((len (length l))
             (mid-pos (inexact->exact (ceiling (/ len 2))))
             (n-element (nth l mid-pos)))
        (cond (( n-element n)
               (aux (take l mid-pos) i))
    (aux l 1))

(defined nth and take for Scheme, almost as defined in Mathematica to resemble [[_]] and Take, which for Schemers is Take is take when receives a positive argument and drop when receives a negative argument. Code is in the end of this blog post.)

This is a usual recursive function with no-side effects that will as fast as possible try to compute the position given the fact that the list is ordered. A simple-minded student B will do in Scheme:

  ;; Returns the position of a given element in an ordered list.
  ;; (give-element '(2 3 6 8 15) 8) => 4
(define (give-element-slow l n)
    (let loop ((l l) (i 1))
      (if (= (first l) n)
          (loop (rest l) (+ i 1)))))

Let’s make the same students define these in Mathematica. So student A:

GiveElementFast = Function[{l, n},
      Module[{lst, i, len, midpos, nelement},
        lst = l;
        i = 0;
        len = Length[lst];
        midpos = 1;
        nelement = Infinity;
        While[nelement != n,
          len = Length[lst];
          midpos = Ceiling[len/2];
          nelement = lst[[midpos]];
Let's take a bunch of benchmarks now.</del>(In fact I did take some benchmarks but unfortunately, posting them along the post would take more time than it should and the results are intuitive.)
What happens is that the time to search a list in Scheme with the Fast Procedure is much larger than the Slow one, and in Mathematica happens exactly the opposite. This is exactly due to the fact that Mathematica Lists are vectors and the Fast Procedure is only really fast if the datatype is a vector since getting an element from a list is O(n) and getting an element from a vector is O(1) (which means that getting an element from a list is done in linear time with the size of the list, and constant in the size of the vector). So, in fact, the approach student B took when developing the functions was the correct one since he probably new the orders of growth in list access, what he didn't knew and that's why his approach fails in Mathematica is that Mathematica cheats you when talking about lists. Student A approach although wise with vectors is naive with lists and or he knows he is working with vectors in Mathematica (which is rarely the case if we are talking Mathematica as a first programming language) or he gets is fast just by luck. Either case, something is wrong and potencially confuses the student. Mathematica is great for symbolic manipulation, data plotting and programming of rather simple software prototypes but extremelly bad to teach programming concepts. Seems simple and straightforward to those programming in Mathematica for a long time but cannot see the damage they are inflicting to their students.


And of course, there are the license issues. Mathematica is cross-platform but also is PLT-Scheme and many others. However, if you find a bug in Mathematica 5.1 (for example, the extremelly annoying bug of numlock not working ok on Linux Systems) you have to wait for the next release (probably a couple of months), if you find a bug in an open source free system you contact the developers and probably in less than a day they put online a binary version of the software working as you wanted to.

<strong>Last Comments</strong>

Surely Mathematica is not useless. Mathematica is a powerful symbolic manipulator with a nice embedded Programming Language, still using it for a course on Programming as a first Programming Language should be considered a criminal offense, and those enforcing its use should revise the course or accept the death penalty.

<strong>Other Code</strong>

(define (nth l n)
    (if (= n 1)
        (first l)
        (nth (rest l) (- n 1))))


(define (take l n)
    (define (take-aux l n)
      (if (= n 0)
          (cons (first l)
                (take-aux (rest l) (- n 1)))))
    (define (drop l n)
      (if (= n 0)
          (drop (rest l) (- n 1))))
    (if (> n 0)
        (take-aux l n)
        (drop l (- n))))

Next page