Lazy sequences and streams

Functional languages have the notion of lazy sequences, which are an abstraction of infinite sequences that are stored using a small, finite amount of memory. It would be wasteful to realize an entire infinite sequence before even using it. The basic idea is to only call the function that generates the sequence when needed, and cache the results. With lazy sequences, you don't blow the stack and the elements in the sequence are not recalculated everytime.

Let's look at how the two most popular and functional JVM languages handle lazy sequences.

Continue reading →

The WebBrowser nightmare

I recently had to use the WebBrowser .NET component in a project. The control is essentially Internet Explorer embedded in a UserControl component. Although the facilities for JavaScript interoperability and DOM manipualtion are pretty great, the control fails to meet simpler needs.

To override keyboard input handing in the control, we need to set the WebBrowserShortcutsEnabled property to false and handle the PreviewKeyDown event.

Continue reading →

Abstract and parameterized types

Scala supports both abstract and parameterized types, which are essentially revamped generics (in Java) or templates (in C++).

First off, methods can be parameterized, in order to abstract a generic type which can be used by it. The apply method in companion objects is the best place to start. Here's an example from the implementation of the List class in the Scala library.

object List {

  // ...

  def apply[A](xs: A*): List[A] = xs.toList
Continue reading →

61 byte selection sort

Here's the absolutely smallest array sorting function in C. It's written by M. Doughlas McIlroy of Darthmouth College, NH USA. It only 67 bytes long (ignoring new-line characters), which is ridiculously impressive. In the function s shown below, a is the starting address of the array, and b is the address of the last element plus one.


This can be made even smaller using recursion and by inferring the type specifiers of global object declarations, which is a GCC hack. In the following function, n is the number of elements in the array a.

Continue reading →