Exercises in Programming Style–Aspects

NOTE : read the rest of the series, or check out the source code.

If you enjoy read­ing these exer­cises then please buy Crista’s book to sup­port her work.

exercises-prog-styles-cover

Fol­low­ing on from the last post, we will look at the Aspects style today.

 

Style 18 – Aspects

You may also know this style as Aspect-Oriented Programming, or AOP for short. I’m a big fan of the paradigm and have often written about it in the past.

Constraints

  • The problem is decomposed using some form of abstraction (procedures, functions, objects, etc.).
  • Aspects of the problem are added to the main program without any edits to the source code or the sites that use them.
  • An external binding mechanism binds the abstractions with the aspects.

 

In her example, Crista used Python’s metaprogramming capability to override the original functions with a new version that has the aspects applied already. Let’s see what we can do in F#!

Starting with the abstractions:

Style18_01

we want to chain them together at the end of the program:

Style18_02

and get the following outputs (note the timing of the function calls have been logged):

Style18_03

Unfortunately, if we try to define the same function twice (once for the abstraction, and then again to shadow it with the profiled version) the F# compiler will bark at us.

But, there’s a easy way to get around this.

Remember how, by opening the Checked module all the arithmetic operators are shadowed with versions that does overflow/underflow checks? We can apply the same technique here:

Style18_04

If we just open the Profiled module we’ll shadow the original abstractions with the profiled versions!

Now, if we chain the abstractions together (the call site) we’ll get the output that we expected.

Style18_05

 

You can find the source code for this exer­cise here.

Exercises in Programming Style–Reflective

NOTE : read the rest of the series, or check out the source code.

If you enjoy read­ing these exer­cises then please buy Crista’s book to sup­port her work.

exercises-prog-styles-cover

Fol­low­ing on from the last post, we will look at the Reflective style today.

 

Style 17 – Reflective

We’re now officially at the halfway mark in this series, I hope you’ve enjoyed the series thus far and today’s style is a funky one!

Constraints

  • The program has access to information about itself, i.e. introspection (see last post on how it differs from reflection)
  • The program can modify itself – adding more abstractions, variables, etc. at runtime

 

In her example, Crista used Python’s metaprogramming capabilities to:

  • dynamically inject additional functions based on the arguments passed into the script
  • eval these new functions and capture the return values into the running application

The metaprogramming capabilities of .Net languages have improved significantly since the availability of Roslyn and the F# compiler service, but it’s still nowhere near what one can easily do in Clojure, Ruby, Python and other dynamically typed languages.

 

First, we need to go and grab the F# Compiler Service package from Nuget.

Then, we need to reference it in our script and follow the tutorial on embedding the F# Interactive (FSI) in our application:

Style17_01

Once we have an instance of FsiEvaluationSession, we’re mostly interested in its EvalExpression method. Before we move on, let’s add another helper function to deal with its result:

Style17_02

Now we can start writing our code as strings, yay! 

Couple of things I noticed whilst experimenting with the following:

  • you can’t open namespaces in the source code
  • you can’t read files in the source code

which is why I used fully qualified names for System.IO.File.ReadAllText, and why it’s only used in composition and not directly invoked in the source code.

Instead, the code that’s captured in the string below will return an extractWords function with the signature

string -> string -> string[]

When we later evaluate it we’ll need to cast the result to that type and invoke the function with the paths to the stop words file and the input file for Pride and Prejudice.

Style17_03

We’ll apply the same approach and create a piece of code that returns a function with the signature :

string[] -> (string * int)[]

Style17_04

and another function that’ll take the word frequencies generated by the code above, sort them and print the top 25 results on screen:

Style17_05

Finally, all the pieces are in place.

Now, we can string everything together (pun intended) by:

  1. evaluating the code snippets above
  2. capture the results and cast them to corresponding types
  3. invoke them with the paths to the stop words file and the input file

Style17_06

and voila!

 

You can find the source code for this exer­cise here.

Exercises in Programming Style–Introspective

NOTE : read the rest of the series, or check out the source code.

If you enjoy read­ing these exer­cises then please buy Crista’s book to sup­port her work.

exercises-prog-styles-cover

Fol­low­ing on from the last post, we will look at the Introspective style today.

 

Style 16 – Introspective

This marks the start of a couple meta-programming related styles which also includes Reflective, Aspects and Plugins.

If you have come from a .Net or Java background then the subtle difference between introspection and reflection might not be obvious. This wikipedia article gives a pretty good explanation:

type introspection is the ability of a program to examine the type or properties of an object at runtime

Introspection should not be confused with reflection, which goes a step further and is the ability for a program to manipulate the values, meta-data, properties and/or functions of an object at runtime.

Constraints

  • The problem is decomposed using some form of abstraction (procedures, functions, objects, etc.)
  • The abstractions have access to information about themselves and others, although they cannot modify that information

 

In her example, Crista used two of Python’s introspective capabilities:

  1. inspecting the stack to see who the caller is and only allow the function to be called from ‘extract_words’
  2. fetching the value of the argument passed into the function

both feel a bit contrived, especially 2.

I don’t know of any ways to do 1. in F#, you can walk the stackframe but it gives you filename, line number, method name, etc. but I didn’t find a way to get the calling function name in any usable form. Since I’m doing this exercise in a F# script might have complicated matters further, as I kept seeing things such as ‘FSI_0004’ as type names.

After giving this some thought, I think a more realistic example in our context here is to use objects to hold data as properties and use introspection to fetch their value.

 

So first, let’s define the two types which we’ll use introspection on:

Style16_02

Style16_03

We’ll use introspection to get at the DataStorage.Words and StopWordsFilter.StopWords properties. But, let’s do that with style and define the dynamic operator to do the heavy lifting for us:

Style16_01

and now we can have a filterWords function that:

  • takes two arguments  – dataStorage and filter
  • dataStorage can be of any type with a string[] property called Words
  • filter can be of any type with a Set<string> property called StopWords

Style16_04

this function has the signature of

‘a -> ‘b -> seq<string>

Perhaps here lies the strength and weakness of this approach:

  • that it’s much more generic than if we had depended upon the concrete types, and would even work with types that I don’t control (and therefore can’t enforce any interfaces upon them)
  • but the constraints on dataStorage and filter are now implicit and you’ll have to inspect my code to figure them out

a much better solution in F# would be to use statically resolved type parameters, but that’ll be out-of-style I think.

Next, we’ll add another function to count the frequency of the filtered words, nothing special here:

Style16_05

Finally, to string everything together:

Style16_06

 

You can find the source code for this exer­cise here.

Upcoming user group talks in UK

Just a quick note to say that I’ll be doing a couple of F# talks at user groups around the UK, so if you happen to be in the area at the time do come by and say hello.

 

Feb 3rd, 6:30pm, London BCS (near the Strand)

7 ineffective coding habits many F# programmers don’t have

Feb 11th, 6.30pm, F#unctional Londoners (at SkillsMatter)

Taming cloud complexity with F# DSLs

Feb 24th, 6:00pm, F# |> Bristol (at the JUST EAT office)

Taming cloud complexity with F# DSLs

March 21st, 6:45pm, F# |> Cambridge (at the Maypole pub)

Taming cloud complexity with F# DSLs

 

Hope to see you at one of these meetups, ciao for now 

Project Euler – Problem 83 Solution

The problem description is here, and click here to see all my other Euler solutions in F#.

 

This is a more difficult version of problem 82, and now you can move in all four directions!

As before, we start by loading the input data into a 2D array:

Prob83_01

and initialize another matrix of the same size to hold the minimum sum leading to each cell:

Prob83_02v2

What we have done differently this time though, is to choose initial defaults:

  • for the top-left corner (0, 0) the minimum sum is itself
  • for all other cells at (row, col) we’ll always traverse right and then down
    • if row = 0, then this equates to only move right until we reach col
    • if col = 0, then this equates to only move down until we reach row

e.g.

Prob83_03

Next, as we did for the problem 82, we’ll add a couple of helper to help us traverse both matrices:

Prob83_04

and we’ll find the new minimum sum to each cell by taking the minimum from the four directions:

Prob83_05

Unlike before, we can’t isolate to optimizing one column at a time, and instead we’ll need to traverse the whole matrix. For better cache locality, we’ll traverse row first and recursively optimize the whole matrix until no more optimization is possible:

Prob83_06

Finally, find the final value for the bottom-right corner of the sum matrix:

Prob83_07

This solution runs in 73ms on my laptop.

 

The source code for this solution is here.