Thursday, July 14, 2005

Unexpected use of exceptions

Typically, when you use an algorithm to determine if a number has strict divisors, you use the algorithm to both factor into primes and to determine primality (no strict divisors found).

But how irritating it is to write an algorithm that can do both efficiently! Because if you are just looking to determine primality, any divisor found already gives you the answer --- so you'd need a check to see if you should stop. But when you want to find all factors, then you don't want to check because it's unnecessary.

And yes you can subclass, and you can do all sorts of complicated stuff, or you can raise a notification when you find a factor! Since notifications' default event handler proceeds, nothing bad happens if nobody is listening. Thus,


      ^[self refinedFactorization isDefinitelyPrime]
        on: ComposedIntegerFoundEvent
        do: [:ex | ex return: false]

Wow... so much nicer!

Observation: usage of when:send:to: within the same process amounts to raising a notification. Think about the implications...

No comments: