Archive for the 'programming' Category

Fussy C++

Posted by mikedaum on June 11th, 2008

So last night I’m all

GslMatrix D;
GslMatrix B;
C.symmetricEigs(B, D.diag() );


But the compiler is all

error: no matching function for call to 'GslMatrix::symmetricEigs(GslMatrix&, GslVector)


See the problem? D.diag() is passed in as a temporary, and the symmetricEigs has it passed in as a reference. Rather than behave rationally, the compiler refuses to consider the possibility that I meant it to pass the temporary by reference, and tells me that it can’t find a proto for what I want to do.

Now I ask you: is this good behaviour on the compiler’s part? Is this what I wanted to do? A nice error telling me that I’m trying to pass a temporary by reference would have been a little better. But is it really an error? What about side effects? I was certainly counting on those in this case, but it refused to play ball.

Anyway, I’m leaning towards my not understanding the situation. Maybe there’s really a technical or spec reason why this error is necessary. For the life of me, I can’t think of one though. So until one of you points out the essential thing that I”m missing, I’m going with this should be a warning at best, but should certainly be allowed.

Oh, and btw, the solution was to create

GslVector d;

one line above and pass that in instead. On the stack like the temporary, but somehow able to give compiler that nice cozy feeling it needed.

Haskell Power

Posted by mikedaum on June 28th, 2007

I’m currently working through the project euler puzzles as a way to learn the Haskell programming language. For one problem I needed to generate the power set of a list (the set containing all subsets). I figured it might be in the standard library, which I don’t know well, so I googled it.

What I found on evan_tech was this mind-blowing code snippet:

import Control.Monad

powerset :: [a] -> [[a]]
powerset = filterM (const [True, False])

Yikes! Seems short…and the first two lines are just the includes and the prototype. The entire meat of the function is in the last line. But does it work?

*Main> powerset [1,2,3]
[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]

Of course it does .. but how. Check out Evan’s site for details. The short form is that it makes ingenious use of the List monad…which is the most confusing monad (IMHO) because lists seem so cuddly and familiar…lulls one into a false sense of security. Basically, the [True, False] says that for each element in the original list, I’m gonna want lists in the output which both do — and don’t include the original element. Makes sense at a high level…but where’s the looping? Well, turns out the List monad defines its >>= operator (bind) internally as concatMap (which is the only way you could do it…if you think about it). So the “Map” in concatMap generates the iteration.

Beautiful.