2011
08.03

Polymorphism is a method of contextualizing a function. Basically, different function forms can be defined for different situations.

Suppose we would like to define a function that can add up three arguments. The basic definition would be as follows;

Add-Bunch(a b c)
{
	Add-Bunch = a + b + c
}

Fine and dandy, it works as expected.

PS C:\Users\Vesa\Kronos.Preview1> .\k2cli.exe .\part4-polymorph.k
K2CLI 0.1
(c) 2011 Vesa Norilo

EXPR>Add-Bunch(1 2 3)
Add-Bunch(1 2 3) => 6

Maybe we would also like to add four numbers. We can utilize polymorphism by providing a second version of the function that does just that:

Add-Bunch(a b c)
{
	Add-Bunch = a + b + c
}

Add-Bunch(a b c d)
{
	Add-Bunch = a + b + c + d
}

Or, if we’re really clever, utilize the first definition in the latter one.

Add-Bunch(a b c d)
{
	Add-Bunch = a + Add-Bunch(b c d)
}

Of course, it’s not very practical to write a separate form for every case.

A General Solution

Let’s think abstractly for a little bit. Adding a ‘bunch’ consists of adding all the elements separately. Finally, there’s just one. I have a hunch we should start with a really stupid-seeming definition:

Add-Bunch(a)
{
    Add-Bunch = a
} 

Add-Bunch(a as)
{
    Add-Bunch = a + Add-Bunch(as)
}

Huh?

Okay, so the sum of a bunch of one is the one element itself. But what about the second form? Based on our earlier knowledge, it appears that is should work for the two-argument case.

What happens in the case of three arguments if we have just these two forms?

When a function is called, it’s arguments are bound to whatever was supplied by the caller. Let’s paraphrase this by unfolding the contents of ‘Add-Bunch’ in a hypothetical function call:

result = Add-Bunch(some-stuff)
/* is identical to ... */
(a as) = some-stuff
result = a + Add-Bunch(as)

There’s a new thing here; defining or binding ’(a as)’ to ‘some-stuff’. Briefly put, this attempts to split ‘some-stuff’ in two parts, defining ‘a’ to be the first part and ‘as’ to be the latter. When ‘as’ is passed to Add-Bunch, it is again splitted into two parts. This may seem confusing, but most of the time it just works - here is a brief example; more detail on the type algebra to be supplied later.

bunch-of-stuff = (1 2 3 4 5)
(a b c) = bunch-of-stuff
/* Result: a = 1, b = 2, c = (3 4 5) */

If you parsed this already I salute you for some serious brain power; you now realize that our odd little two-form definition can handle any number of arguments.

EXPR>Add-Bunch(3)
Add-Bunch(3) => 3
EXPR>Add-Bunch(3 5 9)
Add-Bunch(3 5 9) => 17
EXPR>Add-Bunch(3 5 9 1 2 4)
Add-Bunch(3 5 9 1 2 4) => 24

If this feels slightly mysterious, don’t worry. Part 5 on the staples of functional programs will give you examples of how to use this abstract power in the real world.

No Comment.

Add Your Comment


seven − = 1