Curry: I’m partial to it, so is F#

Another rushed post, thought of in the shower, written before I get to work. This is day 3 of my actually trying to learn and use F#. Everything here is rather rough.

If you groaned at the title then I guess your a functional programmer too 🙂

What do I mean?

In VB or C#, a function/method that has more than one parameter (that is not optional!) requires them all to be called before it will get past the IDE.

What happens if you wanted to return a partial function because you didn’t collect all the needed parameters yet?

In F# functions do not require all the parameters, they just don’t execute until they have them.

Have a look:


let p = [1;2;3] |> List.map(fun x -> x * x * x)
let q x y = x * y / (x * 2 + y)
let d = p |> List.sum

let x = q d 10

let part1 = q 10
let part2 = part1 12

printfn "Value of X: %A - Value of curried function: %A" x part2

printfn "List is now %A" p

As I’ve literally got two minutes before I’m officially going to be late for work, I will clarify this code further.

Also lookout for my fight with Mvvm, Entity Framework and Repository – the controversial extra layer for my data. Yes, I got one working with navigation properties but I have to say, for newcomers to N-tier, WPF and EF5 it is not an easy run. I think my research blog count ran to 30 explorer tabs before I was done!

For those that wonder why so many little blog posts, it’s part of my learning strategy. Reading alone has never been enough for coding work, neither has watching. So my strategy in no specific order is: read & watch, apply and question, write and teach. Ok, take that very last point with a big pinch of salt as I’ve yet to take the time to build any step by step tutorials or explanations.

The small code chunks are also the result of working through Project Euler as a means of apply code Kata practice to my learning.

As I started to code somewhere in my 33rd year of life, I’ve some catching up to do!

New book, Purely Functional Data Structures arrived today!

Why F#?

I can use it within the .net world and it emphasises a contrasting code style / way of thinking. It has type providers-giving me intellisense strongly typed objects from Sql, Odata and even R-a stats language I’m thinking about learning.

Also, I can use my comfortable Vb or even C# for interface work.

Generics, book recommendation

Very brief post.

I’ve used generics a few times; most .net folks have. List(of String), List(of CustomType) are examples. These are built in to .net.

However, if you, like me, are fairly new to many aspects of coding and don’t necessarily know how or why they work.

Simply put, a generic class encapsulates functionality you may have had to implement seperately for each type. So if you wish to build a list of integers, add them up (fold or sum), filter them (select), or apply a function to each one (map), you would be required to implement the appropriate code for each type.

The alternative is defining a single generic class – say List(Of ) and desiging the methods to work with any type. There are some minor niggles you have to contend with however. First one being operator overloading. You can multiply 10*10 but if you pass in a List(Of string), your multiply will get confused. “string” * “string” doesn’t work too good.

You have two options: Overload the * operator OR in .net at least, constrain the generic type. These options are details of generic coding I’m just about to start with, probably in VB and F# so look out for a later post.

Operator overloading can be related, in a way, to method overloading from a base class. At least as an analogy – within your type you specify the behaviour of the operator in question such as * or +. What does it do with the data and what is returned. An example will follow as an edit to this post, when I have one working!

I recommend chapter two in this book for a brief yet brilliant intro to generics, yet it’s Template in C++. The principles are easy to grasp and translate, mentally, to .net languages.

http://www.amazon.co.uk/Structures-Programmers-Premier-Press-development/dp/1931841942

This book is based on C++, not a language I’ve used and one I’m not intending to program lots in. As I believe contextual learning to be very important to me, I tend to read wider than I strictly need to.

Thanks for reading!

F Sharp, LINQ and SQL

Today I found another way to talk to a database. This brings the count up to 4 if you include EF, Custom connectors, Datasets and now, F Sharp Type providers. F# is a great language for rules,specialist tools and data exploration.

Type providers, a feature introduced in F# 3.0, allows for strongly typed access to external data sources without having to be aware of the schema ahead of time.

A great starting book on this intriguing language. F# Survival Guide

Simple example:

open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq 

type dbschema = SqlDataConnection<"Data Source=Katrina\SQLExpress;Initial Catalog=RCPD;Integrated Security=SSPI;">
let db = dbschema.GetDataContext()

db.DataContext.Log |> System.Console.Out

let query1 =
        query {
               for row in db.TableName do
               select row
               }

query1 |> Seq.iter (fun row -> printfn "%A %A" row.SomeId row.SomeName)

I discovered Lambdas – July 2012

A repost from an earlier CodeCall blog. It was the day I figured out, finally, what Lambdas do.

Small parts of programming are actually the most challenging when you are a novice and as I’ve been helped by about a dozen different blog authors in the last few months, I’ll share as well.

For a while I’ve been trying to understand lambdas and their role in LINQ. A lambda is an inline, anonymous function that is also able to access variables just outside of its scope – so if you have a local variable followed by a lambda, you can refer to this variable from within the lambda body. I believe this is known as lambda lifting, but as a newbie, I stand to be corrected.

We return a string that is actually a set of scores separated by a arbitrary characters from a column in a table. A certain scoring system relied on 4 different but known chars to build a classification, so this is how I handled splitting. Copy the code below into Linqpad to see the result. The values in the string are stored in a dictionary of <String,Integer>.

Here we have LINQ with a nice Where condition that relies on a function to select items into a dictionary. The single line syntax finishes with another simple pair of splits yielding the key

Function RiskSplit( ByVal riskbreakdown As String, splitStrings As List( Of String)) As Dictionary(Of String, Integer)
    Dim splitchars = { "#", "@" ,"%" ,"+" }
    Dim partList = Function(a As Char) (
                From risk In riskbreakdown.Split(a) Where risk.Contains(ChrList(risk,splitStrings))).ToDictionary(Of String,Integer)(Function(risk)risk.Split(":")(0),Function(risk) risk.Split(":")(1))

    Dim temp As new Dictionary( Of String, Integer)
    splitchars.dump

    For each ch in splitchars
    For Each item In partList(ch)
        if temp.contains(item) = false then temp.Add(item.Key, item.Value)
    Next
    Next
    Return temp
End Function

Private Function ChrList(risk As String, splitsStrings As List( Of String)) As Boolean
  Return splitsStrings.Any( Function(item) risk.Contains(item))
End Function

Sub Main
    Dim splittest = "ADC:2:8:7:50:5:300:True%Test1:2:True:24/05/2011#Sample:1:True:24/05/2011#TomatoSample:2:True:24/05/2011%Muppets:4:True:24/05/2011@Ability:5:True:24/05/2011Health:4:True:24/05/2011@Test:6:True:24/05/2011"
    Dim listtest as new list(of string ) from {"Tomato Sample","Sample","Test","Dementia","Mobility"}
    Dim risks = risksplit(splittest, listtest)
    risks.dump
End sub

When the Dictionary wasn’t enough?

In the spirit of code katas, I decided to see if I can get the gist of a design pattern today. In the process a second design pattern slipped in. This is my second blog post and being a novice, I’m not intending to tutor, but show my own stumblings as I figure out context of how and why certain ideas exist. Here I create mini abstract factory. This is the first stage in my understanding. Notice private constructor so that one must use the static/shared function. The door could be a super class OR simply an interface-subject of my next blog. Needs a combobox on a form to run. `

Pub

lic Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
     For Each d In door.doorlist
         ComboBox1.Items.Add(d.Key)
     Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
     Dim door As door = door.returnNewDoor(ComboBox1.SelectedItem)
     door.ShowDoor()
End Sub
End Class

Class door
Private _door As doorType

Shared Property doorlist As New Dictionary(Of doorType, door) From {{doorType.Asian, New door(doorType.Asian)},
                                                                      {doorType.Euro, New door(doorType.Euro)}, 
                                                                    {doorType.Indian,New door(doorType.Indian)}}

Private Sub New(door As doorType)
     _door = door
End Sub
Shared Function returnNewDoor(door As door.doorType)
     Return doorlist(door)
End Function
Enum doorType
     Asian
     Euro
     Indian
End Enum
Public Sub ShowDoor()
     MessageBox.Show(Me.ToString)
End Sub
Public Overrides Function ToString() As String
     Return _door.ToString
End Function
End Class

I’m blogging as I code here, so I decided to figure out how to use Interfaces as a type and added in the specialised classes. These are not subclasses, I get polymorphic behavior purely via the Interface. Which is nice. Also, stripped out the excess parameters in the handlers.

Public Class DoorInterfaceDemo
    Private Sub Form1_Load() Handles MyBase.Load
        For Each d In door.doorlist
            DoorCombo.Items.Add(d.Key)
        Next
    End Sub
    Private Sub DoorCombo_SelectedIndexChanged() Handles DoorCombo.SelectedIndexChanged
        Dim iDoor As IDoor = door.returnNewDoor(DoorCombo.SelectedItem)
        iDoor.showdoor()
    End Sub
End Class
Interface IDoor
    Sub showdoor()
End Interface
Class door
    Private _door As doorType
    Shared Property doorlist As New Dictionary(Of doorType, IDoor) From {{doorType.Asian, New AsianDoor},
                                                                 {doorType.Euro, New EuroDoor},
                                                                 {doorType.Indian, New IndianDoor}}
    Private Sub New(door As doorType)
        _door = door
    End Sub
    Shared Function returnNewDoor(door As door.doorType)
        Return doorlist(door)
    End Function
    Enum doorType
        Asian
        Euro
        Indian
    End Enum
End Class
Class AsianDoor
    Implements IDoor
    Private Property _door As String
    Sub New()
        _door = "Asian Door Here"
    End Sub
    Public Sub ShowDoor() Implements IDoor.showdoor
        MessageBox.Show(_door)
    End Sub
    Public Overrides Function ToString() As String
        Return _door
    End Function
End Class
Class EuroDoor
    Implements IDoor
    Private Property _door As String
    Sub New()
        _door = "EuroDoor"
    End Sub
    Public Sub ShowDoor() Implements IDoor.showdoor
        MessageBox.Show(_door)
    End Sub
    Public Overrides Function ToString() As String
        Return _door
    End Function
End Class
Class IndianDoor
    Implements IDoor
    Private Property _door As String
    Sub New()
        _door = "IndianDoor"
    End Sub
    Public Sub ShowDoor() Implements IDoor.showdoor
        MessageBox.Show(_door)
    End Sub
    Public Overrides Function ToString() As String
        Return _door
    End Function
End Class

`

Alternative to Case?

A couple of months ago I came up with the notion of using a dictionary to avoid having a huge case statement. For a real short period it was a little golden hammer too. Here is where I’ve used it twice.

First in my code generator for mapping columns in an Access database to a property type: And here where I return a variation of a query, in LINQ, based on selected options.

Private Function ReturnDetails(residentID As Integer, Optional field As String = Nothing)
Dim ID = queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.ID).First

Dim queryAction As New Dictionary(Of String, String) From {{"DOB", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.DOB).First},
                                                           {"RoomNumber", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.RoomNumber).First},
                                                           {"Allergies", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.Allergies).First},
                                                           {"PreferredName", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.PreferredName).First},
                                                           {"Nationality", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.Nationality).First},
                                                           {"Religion", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.Religion).First},
                                                           {"Keyworker", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.Keyworker).First},
                                                           {"Gender", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.Gender).First},
                                                           {"NI", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.NI).First},
                                                           {"Admission Date", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.AdmissionDate).First},
                                                           {"Discharge Date", queryDetails.Residents.Where(Function(x) x.ID = residentID).Select(Function(x) x.DischargeDate).First},
                                                           {"ID", ID}}
If queryAction.ContainsKey(field) Then
    Return queryAction(field)
Else : Return queryAction("ID")
End If

End Function

Of course, to go beyond the one liners, I’ve got to consider multiline sub lambdas or work on a strategy/template pattern. However it was nice to have an in between alternative to Case statements by having learnt lambdas.

Later that day I did find a blog post discussing this in much greater depth; he even included a defaultable dictionary in C#. When I locate the link, I’ll put it here.