If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, October 26, 2011

Code vectorization examples

To greatly reduce complexity and even benefit from greater performance often a technique called 'code vectorization'.

Example 1:

Let's check the outcome of the vectorized formula:

Example 2:

Tuesday, October 25, 2011

Using higher order functions with Octave

I was working on implementing the sigmoid exercise from the MachineLearning class. The assignment stated the following requirement:'Your code should also work with vectors and matrices'. But I already sensed that this is calling for using higher order functions.

The sigmoid function basically is defined as

Now you could of course write some for loops each time you want to apply a function to each element of a matrix, it makes more sense to write a generic mapper function which takes two parameters: a matrix (or vector) and a function to be applied to each element of that matrix. This mapper function then instead returns a new matrix. First thing to do was checking if Octave supported higher order functions. It turns 'feval'comes to the rescue.

Now for demonstrating this works i wrote a simple function which doubles its argument:

Now from the command line:

As Davy Meers pointed out Octave also supports anonymous functions which are even more powerful.

Monday, October 24, 2011

Best practices XSLT

I'm pleased to see that my own findings in programming with XSLT match the ones from Andrew Welch:
  1. don't use xsl:for-each, use xsl:apply-templates
  2. don't use named templates, use xsl:apply-templates with a mode
  3. if a template just contains a choose/when, separate out the branches into individual templates
  4. instead of xsl:value-of use xsl:apply-templates
  5. one large template is bad, lots of specific small templates is good
Regarding (4): xsl:value-of will create a text node in the result tree, xsl:apply-templates will ultimately apply templates on the text node where the default template will kick in and copy it to the result tree... so the effect is the same, however in the latter case you are making it available for overriding.

so for example:

you could do:

or you could do:

both will output the same result.

Now if a requirement comes in to wrap the type in <b>, but only if its 'beer', if you have used apply-templates you can just add the

...and then go home. However if you have use value-of earlier on,
you would need to go and modify that template first to change it to an apply-templates anyway.