Uh…  No.  I get this rhetorical question from fellow developers a lot.  LINQ uses the “from-where-select” syntax (with the “from” and the “select” in a more sensible order) from SQL but that’s only to give developers a familiar model.

LINQ can be used to query relational data sources like, SQL Server, Oracle, MySql, etc.  LINQ can also be used to solve general programming problems in a functional way.

Go take a quick look here for a rather contrived puzzle example.  If you still think LINQ was made just to query relational data after looking at it…  I’m not sure how to make it clearer for you.

Tags Categories: LINQ, Software Development Posted By: Carey Cilyok
Last Edit: 13 May 2010 @ 12 19 AM

EmailPermalinkComments (0)
 02 Feb 2010 @ 4:58 PM 

For a while I’ve been meaning to collect the list of tools that I typically install on any development workstation.  Instead of keeping that list to myself, I’m making it available to anyone who wishes to use them as well.  I’ll keep the list pretty short but a short list of tools a developer uses can be quite large.  If you want a better list of tools, I suggest you occasionally visit Scott Hanselman’s blog and tool list.

The tools I typically use will always be available on my tools page.

Tags Categories: Software Development Posted By: Carey Cilyok
Last Edit: 02 Feb 2010 @ 05 04 PM

EmailPermalinkComments (0)
 17 Nov 2009 @ 3:29 PM 

If you do a search on “to GAC or not to GAC” you’ll get mixed messages with a bias towards “not to GAC”.  I couldn’t disagree more strongly with those who urge you not to use the GAC “unless you work for Microsoft, and then only if you’re working on the .NET Framework” (quote not linked to save the writer the embarrassment).  No need to sugar-coat this one…  The folks making those recommendations clearly know very little about development on the .NET platform.  The only generosity I can muster for these people is perhaps they’ve never worked in an organization with more than 2 developers and have never had to write a shared assembly.  Perhaps we can blame Microsoft for having promoted the term “xcopy deployment”.  Perhaps they never lived the Win16 to Win32s to Win32 to COM transitions. Perhaps these people are the village idiot.

Some background first…

What is the GAC?

GAC stands for the Global Assembly Cache.  Without going into excruciating minutiae, the GAC is simply a repository of shared assemblies, managed by the operating system, and used by the Common Language Runtime (CLR) to resolve references to shared code.

How does the CLR resolve assembly references?

For a full description of how the CLR resolves references, look at the MSDN article “How the Runtime Locates Assemblies”.  The basic steps are these:

  1. Determine the correct version of the required assembly.
  2. Has this assembly already been bound and cached?
  3. If the assembly is not already bound, look in the GAC.
  4. If the assembly isn’t in the GAC, check the PATH.

Actually, “check the PATH” is grotesquely over-simplified.  The actual process is called “probing”, for full details on that process look at the MSDN article “Step 4: Locating the Assembly through Codebases or Probing”.

So for all of the pundits out there that think that just dropping your assembly into the application directory is all there is to it, I’d suggest a little reading.  As you can see, the application directory is actually checked AFTER the GAC. Unless an assembly reference has already been “bound”, the GAC is the first place the CLR will look to attempt to resolve the reference.

“to GAC”?

If we’re talking about an assembly that is shared by more than one application in your application suite then the answer is a resounding yes.  Will you ever need to maintain two versions of the same assembly in the deployed environment?  If so, another resounding yes.  Will your application implement a dynamic loading mechanism via a configuration file to load a “snap-in”?  If not yes, it’s certainly a possibly.  After all, if I’m going to specify a code base via a configuration file and call System.Reflection.Assembly.Load or System.AppDomain.Load myself, then I’d like to have the option of specifying a fully qualified assembly name.  Then again, I may want to circumvent the “standard” binding order from above so that I can implement a sort of “drop-in” deployment and implement the code to look in the application directory first.  Either way, the option of using the GAC is still totally valid contrary to prevailing net wisdom.

“not to GAC”?

There are obviously situations where you don’t want the added deployment overhead of using the GAC.  Using the GAC isn’t free after all, you need to setup your development environment to place your new assemblies in the GAC, remove the last compiled version (if you’re so inclined), etc.  I never said that there was no price to pay.  Are you deploying a “resource assembly” that is only applicable to one application?  Then don’t put that in the GAC, there’s no compelling reason to do so.  Is the assembly your deploying shared at all?  If not, then don’t put it in the GAC.  Again, no compelling reason to do so.

If you don’t want to use the GAC based on some bizarre “principle”, then use Linux or some other platform.  (Yes, one developer once told me he wouldn’t use the GAC out of principle. Huh??)  After all, I love Linux and other platforms as much as the next guy.  Stop proclaiming that the “GAC is evil” (Again, direct quote from a developer) unless you know what you’re talking about.

The point I’m trying to make is that “to GAC or not to GAC” is a more informed decision than many of the absolutist “not to GAC” stances you’re going to read out there.

Tags Tags:
Categories: Software Development
Posted By: Carey Cilyok
Last Edit: 17 Nov 2009 @ 05 07 PM

EmailPermalinkComments (3)
 13 Aug 2009 @ 12:11 PM 

I know I have a readership of almost 2 people and that they waited eagerly to hear my prolific wisdom, so I must apologize for my lack of regular posting.  It’s pretty clear I maintain this blog for me and me only.  I didn’t do it for a following – most of what I write is for an audience of one…  Me.

If you do actually read my blog let me tell you what’s new.  I’m still turning the functional programming crank and trying to learn the discipline.  I’ve also picked up several new topics to understand as well with Power ShellOslo, M, and Python (actually IronPython).  Unity and Enterprise Library 4.1 have moved back up the must learn list as well.  I’ve also been playing with the Visual Studio 2008 SDK.

At work we’re also trying to establish our build environment and I spent a bit of time writing a “best practices” sort of document for arranging the code repository, directory structure, operating system environment set up, and organization of Visual Studio solutions and projects to fit into it all.  I’ve considered generalizing that document and posting it here as I’m a little tired of creating project specific implementations of it.  This effort forced me to hand off the DSL project to a co-worker, so he got to have all the Oslo and M-grammar fun.

I’ve learned a lot of pretty cool new things and would love to sit down and write something meaningful on each and every topic.  Unfortunately, it seems all I have time for is a post explaining why I haven’t.  If you’ll hang with me, I promise I’ll fix that situation as soon as I can.  ;-)

Tags Categories: Career, Enterprise Library, Oslo, Software Development, Unity Posted By: Carey Cilyok
Last Edit: 13 Aug 2009 @ 12 18 PM

EmailPermalinkComments (0)
 16 Jul 2009 @ 10:27 PM 

A good friend of mine, Greg, appeared as a guest speaker on a local radio talk show this week.  Greg is a bit more conservative than I am and does not share my appreciation for President Obama but…  He worked in a plug for Haskell!!!  How strong is that?

Oh, and since I’m talking about Greg being a geek that can speak – I’m giving him this plug.  Look at what he wrote for his daughter.  Makes me proud to be a geek sometimes when I get to call guys like that friends.

Tags Categories: Family and friends, Software Development Posted By: Carey Cilyok
Last Edit: 16 Jul 2009 @ 11 04 PM

EmailPermalinkComments (1)
 10 Jul 2009 @ 2:20 AM 

It’s incredibly embarrassing to me that I have to make the following admission:  I had no idea what Microsoft “Oslo” was all about.  Oh, I’d heard of it but didn’t look at the scope and objectives.

I’m a true believer in using DSLs as a method of accelerating the software development process.  Well, that’s the objective of Oslo.  I’ve now downloaded the Microsoft “Oslo” May 2009 CTP and am starting to play with it.

I might be slow but, at least, I’m clueless.

Tags Tags: , ,
Categories: Career, Oslo, Software Development
Posted By: Carey Cilyok
Last Edit: 10 Jul 2009 @ 02 23 AM

EmailPermalinkComments (0)
 04 Jun 2009 @ 1:07 AM 

I will attempt to keep this post accessible to a general audience although it is about software development. My intent is to explain my long held philosophy of getting the domain experts as close to the software development process as possible. Since they are seldom experts in software development, delving deep into esoteric software topics is the quickest way to run them off. There will be some pretty geeky stuff buried in here but it should be easy to separate it from the general philosophy.

I’ve been interested in Language Oriented Programming (LOP) and Domain Specific Languages (DSL) since graduate school and my first professional software development job at Intergraph Corporation. I didn’t call the concepts LOP and DSL but that’s what I was doing. One of my last courses in graduate school was on compiler and language theory and I wrote parsers and translators early on at Intergraph. I’ll come back to this later.

First let me explain to the non-developer types who might be reading a little about how software gets developed.

The essence of software development is solving problems. To solve a problem, you have to understand the problem. To understand the problem, you have to learn about the discipline (or domain) where the problem resides. To learn the domain, you need to interact with an expert in that domain. This interaction is known as requirements gathering to programmers. Then the development team writes a requirements document and, if you’re lucky, the domain experts will verify that the development team interpreted the interactions with them correctly and captured the requirements accurately. In larger organizations and software development environments, programmers usually do not interact with the customer representative directly. Often the customer isn’t the domain expert, they are relaying information gathered from the domain experts within their organization. So, programmers get a “requirements specification” that was told to an intermediary (like a system engineer or project manager), from another intermediary who had spoken with the domain experts, then interpreted to the programmer.

Now, I want you to know that what I just described a pretty thin layer of abstraction between the domain expert and the programmer. In some instances, there are more layers between the two. There are plenty of codified software processes that try to address this issue. There are whole industries built around the concept of telling you how the process of software development is supposed to be done including the requirements gathering step (You don’t want to get me started on that, that’s a whole new post). The other developers reading this post will tell you that I just described a very small part of “the process”. There are a lot more steps. If you want to know how complicated it can get and how many more steps there are and you have millions of dollars to spend, the Software Engineering Institute at Carnegie Mellon will be happy to teach you how to become a CMMI Level 5 organization and spend 98% of your software development budget on “the process”, leaving 2% to actually write the software. Very profitable little hustle business the SEI has don’t ya’ think? But, I digress.

To be fair, there are software processes that are better. To learn about some of them, look up agile software development techniques.

Eventually, larger organizations started to understand that “process” could not address this problem of interpretation and they started hiring “subject matter experts” (SME – usually pronounced “smee”) to work directly with the programmers. So let’s proceed with the rest of this post assuming that the programmer and SMEs get to interact directly. As a point of interest here, I share an office with one of the SMEs for the project I’m currently working on. Even cooler is that his domain expertise is in flying Blackhawk helicopters. It gets better on my current job too. My direct contractor boss is also a SME (Apache helicopter pilot), another of our project managers is yet another Blackhawk pilot and I’m told we’re hiring another pilot. From a programmer’s perspective, this is a great situation. If I have a domain question I don’t even get up, I just say “Hey, Bernie.”

Right now Bernie has to define a lot of the concepts that I will be working on. These concepts include vocabulary and rules which describe the elemental properties of the problem domain. It sounds a lot like he’s putting the language of flying a Blackhawk down in requirements.

Finally, we’ve reached the core of this post – bridging the gap between subject matter experts and programmers.

What if Bernie and I were to define a language (or a collection of smaller languages) that captured the problem domain concepts and the software could be directly written from Bernie’s description in this language? What if that language was core domain logic for the software? That is a domain specific language (DSL).

Bernie does exactly what his job is supposed to be but writes down his expertise in our DSL. Now my job would become writing software that I understand very well, parsers, abstract expression trees, emitters, implementing visitor patterns, etc… Mmmm. Real geek stuff. I spend my time on the things I’m actually an expert. The defects I would be fixing have to do with how the requirements Bernie writes are translated into the actual instructions in the software. Think about that statement for a moment. I spend my time working on ensuring that the requirements are correct. Once the system had matured Bernie and I would reach a point where we knew the DSL was always being translated properly and we could now work on expanding the behavior of the software through our DSL and NOT by writing new code, C# and the .NET Framework in the case of my organization.

The many layers of interpretation described earlier have now been replaced by a single, automated step that can be refined and extended. This is such a powerful concept that someone should write a book on it!

What I’ve just described is what Martin Fowler calls an “External DSL”. My fellow developers that I’m trying to evangelize to here have all written what Fowler calls an “Internal DSL”. An internal DSL is what we write when we write an application programming interface (API), a software development kit (SDK), and even a basic object model (classes, methods, etc.) with limited scope. If you have to capture the concept of a “user” in your application you’re going to write some structure or class that represents a user. The C# language has no native construct for a user in your domain so you had to extend the C# language and once you did, you had created an internal DSL.

Plenty of DSLs exist that programmers are familiar with. Structured Query Language (SQL) used to query data from a relational database system is a prime example. Programmers and database administrators write queries in the SQL DSL, then Microsoft SQL Server, Oracle, or MySQL interprets that SQL and inside actual C, C++, or even assembly language instructions get executed. If you want a simple demonstration of the value of a DSL go write a complex JOIN in C++.

Let’s go back to my first job at Intergraph where I worked for the Electronic Design Automation (EDA) division (the division was later sold and is now Mentor Graphics). I was 24ish and just out of graduate school and honestly a little nervous. I’d finally be working beside professional software developers. We wrote software to help electrical engineers design application specific integrated circuits (ASIC), programmable logic devices (PLD), programmable logic controllers (PLC), etc. This was the 1989-1992 time frame, extensible markup language(XML) wasn’t around, hell, the WWW wasn’t around yet. So, there were lot’s of different file formats to describe all types of aspects of EDA. When I got to Intergraph I was asked to fix a bug in a “netlist parser”. I was told that “netlisters” were constantly breaking and that parsing netlist files was a huge issue and they usually put new programmers on fixing those bugs to get their feet wet. So, I got the source and much to my shock, it was a hard-coded conglomeration of nested conditionals… if this, then expect this or that, else if not that, then this if, switch/case… Horror. And this was the parser for just one of the many netlist formats our software had to support. I suddenly understood why netlist parsing was a big deal. Intergraph had 5 other additional and experienced developers working on maintaining netlist parsers.

Then I found out that many of these netlist formats either had relatively trivial grammars to capture or the Backus-Naur Form (BNF) grammar specification was around. So, I started up vi and started writing LEX and YACC specifications to describe the grammar of the parser I was supposed to just be fixing a bug in. I wired together new MAKE files, stabilized my builds and started tweaking the grammars until I could parse every netlist example we had for this particular format. It took me 4 weeks to fix one bug. There were about 12 different netlist formats. The netlist group accounted for about 30% of the data defects the EDA division had and accounted for about 2% of the total source code. I rewrote the rest of the parsers in LEX and YACC. The defect rate dropped to almost 0 about 4 months after I was asked to fix my first defect. The only defects we had after that typically dealt with non-standard netlist formats from other tools. And were always a pretty easy addition or exceptional case in the BNF specification held in LEX and YACC files. So, the netlist development “team” was spread out to other areas and netlist maintenance was no longer a huge issue. I then got assigned to write all parsers for anything we ever had to parse.

None of that was meant as bragging. Far from it, I had just come from a pure Unix environment in school into an environment that had only recently transitioned from VAX/VMS to Unix on workstations. They were still learning the tools and environment and I was already very familiar with it. Unix has a pretty rich environment based around DSLs like awk, troff, etc. based on grammars processed with LEX and YACC. I had also just recently had a graduate level compiler theory course and had been using LEX and YACC at school. The guys I was working with had never heard of LEX and YACC and many had long since forgotten school work. I just stumbled into a problem I was particularly well-suited to solve.

The real point of the story was that I used 2 DSLs to fix the problem. LEX lets you specify the lexical rules for a language (the alphabet and vocabulary) and YACC lets you define the language rules for combining the lexical elements (the sentences and paragraphs). This is the essential process programmers use to write a parser for a new language. We first specify a grammar that describes the language then construct a parser in terms of that grammar. Using LEX and YACC the construction step is automated. To be absolutely precise I used 3 DSLs because MAKE uses another DSL to automated building software.

Throughout the software development discipline DSLs are scattered into all corners. Clearly, developers know DSLs are useful. The problem is that many developers don’t call them domain specific languages. Hence, the problem gets extended because the power of LOP and DSLs aren’t recognized by many developers and pushed to the next level – the end user and domain expert – even though important publications have pointed out the power of DSLs for going on 15 years now. The concepts have obviously been around longer than that but the tools and support to effectively employ LOP/DSLs have really blossomed in the last 10-15 years.

Let’s speculate for a moment. Natural language processinghas advanced considerably in the last 10 years. It still has a way to go but if we worked within a restricted subset of the English language we can conceive of a DSL that was very intuitive for the domain expert. Not only would it be intuitive it could be pretty close to natural spoken English. I’m using English as my example because, 1) I can speak English and 2) syntactically English is pretty difficult to parse because it can be very context sensitive.

Plenty of graphical examples of DSLs exist as well. The Unified Modeling Language(UML) is an example of a graphical DSL. Schematics for electrical circuits are graphical DSLs.

In order to define the basic classes that constitute my object models I often approach the problem as if I were going to write a DSL.  It’s a great way to organize my thought process and it lays out a narative of use for the obejct model.  A very handy tool when you write APIs and SDKs like I do most of the time.  It tends to let me develop a natural way for other developers to approach using my SDKs.  I propose that if all developers of APIs and SDKs approached the problem from a LOP perspective that APIs would be more usable and intuitive.

Creating and maintaining a DSL does have overhead and additional development costs so one must weigh that cost against the long term benefit.  But, I contend that if your application will have any significant longevity then the benefit is clear, at least, to me.

If you’re not a developer I request that if you find yourself apporached by a developer to be a domain expert you remember this blog post and understand the developer’s efforts.  Perhaps you will have some additional shared understanding of the joint objectives you have with them whether a DSL is the goal or not.

If you’re a developer I hope that I’ve convinced you that a LOP approach and a DSL is an option you should consider.

Tags Tags: ,
Categories: Career, Software Development
Posted By: Carey Cilyok
Last Edit: 23 Jun 2009 @ 12 22 PM

EmailPermalinkComments (1)
 21 Apr 2009 @ 10:59 AM 

ADDENDUM: In a comment to my “Why F#?” post Greg pointed me to a thought provoking article over at Object mentor.  Go check it out.

I’m still waiting for my “ah-ha!” moment with functional programming.  I may be closing in but I’m still falling just a bit short.  I think I’m on the correct line of investigation though.  Once I found this line, I thought it might help you if I shared it before you have to stumble around with functional programming until you find it.  Perhaps, this “starting point” is apparent to everyone except me.

Working with lists of things is pretty common in functional programming implementations.  Recursion is the common method of iteration over lists.  What’s the most common limitation of recursion?  Of course, overflowing the stack.  So, you soon need to learn to refactor recursive functions to use “tail recursion“.  Examples of tail recursion in basic FP tutorials and courses soon lead you to the topic of “folds” over lists.  Studying folds and lists may lead you to the concept of catamorphism.  And so on.

I thought I would write an insightful post detailing some of these concepts but quickly decided that I would just compile a somewhat ordered set of links.  Some are theory and some are related to F#.  The links to background theory are generally to Wikipedia while the links targeted at F# will generally be to blog articles, most notably, Brian McNamara’s blog and a series of posts I’m reading through.  The following sequence of links should be read/learned in order.  Clearly, some of them could be paralleled and the order isn’t written in stone but I have tried to order them so that they are coherent.  The link to functional programming already shown in this post is probably a must-read preliminary to set context.

Some background theory:

Why Functional Programming Matters
High-order functions
Laziness
Anonymous functions (lamdas)
Fold (not that Map and other HOFs aren’t important)
Catamorphism
Currying
Closures

Now for some practical articles:

F# function types: fun with tuples and currying
Catamorphisms, part one
Catamorphisms, part two
Catamorphisms, part three
Catamorphisms, part four
Catamorphisms, part five
Catamorphisms, part six
Catamorphisms, part seven
Catamorphisms, part eight (just for Brian’s sake to be complete)
How does functional programming affect the structure of your code?

The series of posts that Brian has written about catamorphisms is great.  Doing web searches on catamorphism lead me to his series and I’m very grateful that he’s written the series.  I think trying to understand them otherwise would take me an order of magnitude more time.

It was duing the study of catamorphism that I got my first little spark of self-actualized functional thinking.  Maybe I’m biased now but if anyone out there gets the “ah-ha!” moment because of going through the links I’ve pointed out, then I’m a happy guy.  I’ll be even happier when the light-bulb finally stays lit for me.

Tags Tags: , ,
Categories: Software Development
Posted By: Carey Cilyok
Last Edit: 21 Apr 2009 @ 10 50 PM

EmailPermalinkComments (0)
 24 Mar 2009 @ 5:56 PM 

Made ya’ look.  But had I been serious, my wife assures me that I’m magnificent.

Actually, I’m exposing how inept and bumbling I am with LINQ and F#.  Granted, I’ve only just begun trying to integrate the concepts into my toolbox but I haven’t felt this technologically-naked in a long time…  Like ever. 

It’s really not LINQ that’s causing issues.  It’s pretty straight forward and doesn’t apply to my functional programming (FP) ignorance.  Nor is it the F# language.  It’s trying to force myself to “think functional”.  I know I posted about this yesterday but since I mentioned that I’m doing essentially CS 101 exercises to learn the concepts, I might as well post the results for all to see.  You’re welcome to grade me.  I will point out that the solutions, while not really FP, do show off cool things about the technologies and introduce some FP building blocks.  Before we get started, I want to acknowledge the excellant tutorial written by Eric White that is referenced in this post.  Additionally, this blog post while editorial in nature, gives plenty to think about and a place to begin investigating the big, initial question “Does FP matter?

The first problem on the Euler Project list is:  Add all the natural numbers below one thousand that are multiples of 3 or 5.  Simple enough, and for my purposes a perfectly trivial thing to go do in LINQ and F#.

Solution in LINQ

 I did implement the solution using the two different syntax notations (IEnumerable and query) so you could get a look at the coding options available. 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ProjectEuler.LINQ.Solutions

{

    /// <summary>

    /// Project Euler solution for Problem 1

    /// </summary>

    /// <remarks>

    /// Add all the natural numbers below one thousand that are multiples of 3 or 5.

    /// </remarks>

    public static class Problem1

    {

        /// <summary>

        /// Add all the natural numbers below one thousand that are multiples of 3 or 5.

        /// </summary>

        public static int Solve()

        {

            // The solution using the LINQ IEnumerable syntax

            var answerIEnumerable =

                Enumerable.Range(1, 999).

                Where(x => (x % 3 == 0) || (x % 5 == 0)).

                Sum();

 

            // The solution using LINQ query syntax

            var answerQuery =

                (

                    from x in Enumerable.Range(1, 999)

                    where (x % 3 == 0) || (x % 5 == 0)

                    select x

                ).Sum();

 

            return answerIEnumerable;

        }

    }

}

 

The first thing we notice about the solution is its really short.  One of the advantages of using FP techniques is that they reduce the amount of code that has to be written.  This clearly leads to fewer defects and higher developer productivity.  Next, look at how easy it is to process a list of anything.  In this case it’s just a list of integers but we can just as easily process a list of objects.  Consider doing exactly the same implementation using straight forward C# code to iterate over the list of integers and accumulate the answer.  Here we accomplish it all with one program statement.  Again, notice the two different syntax styles available.

Is VB back?  No…  You see the var keyword in the solution and some of you may be tempted to think of variants from Visual Basic 6.0.  Don’t.  var is a keyword introduced with C# 3.0 to implement a language feature called type inference (also called anonymous types).  The variables answerIEnumerable and answerQuery are both 100% strongly typed at compile time.

Examining the code a little closer we can dig out other FP influences.  Look at  Enumerable.Range(1, 999).Where(x => (x % 3 == 0) || (x % 5 == 0)).  See anything unusual?  The static call to Enumerable.Range(…) returns an IEnumerable interface.  It appears that IEnumerable implements a Where method.  It does but it does so because we included a reference to System.Linq.  What is going on here is the use of something called an extension method.  Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.

Of course there’s “x => (x % 3 == 0) || (x % 5 == 0)” lambda expression.  Follow the link provided and read Eric White’s explanation, its quite good. 

Solution in F#

Nothing really exciting about the F# implementation other than an example of using the let key word.  We do essentially the same thing as in the LINQ solution but in the F# syntax.  Not much FP here; and totally breaking FP purity with the use of the printfn call.

#light

 

// Project Euler solution for Problem 1

// Add all the natural numbers below one thousand that are multiples of 3 or 5.

 

let result =

    List.sum(

        [0 .. 999] |>

        List.filter(fun x -> (x % 3 = 0) || (x % 5 = 0))

    )

 

printfn “Add all the natural numbers below one thousand that are multiples of 3 or 5.\nAnswer is %d” result

System.Console.ReadKey() |> ignore

Hmm…  Even shorter.

Specific to F# is that #light directive.  F# is derivative of OCaml the #light directive tells the F# compiler to relax some of it’s syntax rules to make your F# code portable back to OCaml.  Of course, our example above is not portable because we use the System.Console .NET namespace.

Notice the use of the |> notation.  This operator is the forward pipe operator and allows us to string the output of one operation into the input of another.

We also use the fun operator.  This is the syntax for anonymous functions (lambda expressions) in F#.  There is a second keyword for defining functions in F#, oddly enough, it’s called function.  One of the principle differences of the function keyword is that it allows you to to use pattern matching (not shown in our example).

We’ll drift for a moment to introduce a couple of F# concepts since we mentioned pattern matching.  Pattern matching in F# is a flow control construct that acts somewhat like a case statement in C#.  Here’s an example:

let poolPlayer name =

  match name with

  | “Efren Reyes” -> “Perhaps the best that’s ever been”

  | “Shane Van Boening” -> “Deaf kid, sure plays a mean 10-ball”

  | “Jeanette Lee” -> “Plays as good as she looks”

  | _ -> “Don’t know ‘em…  Must be a fish” 

 

Essentially take a single value and match it to something else.  The right hand side of each -> could be an operation of some form instead of a literal value as shown.  Hence, you can use pattern matching to do conditional processing on the input.  Now, since the function keyword allows for pattern matching and pattern matching operates on a single value, the function operator can only take a single parameter.  So in order to define a function with 2 parameters, we’d have to resort to something like:

let x1 = (function x -> function y -> x + y ) 1 2

Nasty.

That’s where the concept of a tuple comes in.  A tuple is an immutable data type that can contain multiple values.  The syntax is simply to group the values inside of parentheses.  So our nasty looking function becomes:

let x2 = (function (x, y) -> x + y) (1, 2)

Much better.  Of course, this implies that pattern matching can handle tuples, which it can.

Since we’ve already seen it in action so much let’s talk about let.  Our example uses a the let keyword.  let operates much like the word let in mathematical disciplines.  It defines the preconditions of the problem to be solved or proof to be derived.  let binds a value to an identifier.  We don’t show it above but  let can be used to define an immutable value (think constant) as in:

let x = 10

let y = 5

let diagonal x y = System.Math.Sqrt(x*x + y*y)

Here x and y are immutable values of 10 and 5 respectively, and will never change.  While the 3rd statement binds the identifier diagonal to the function value System.Math.Sqrt(x*x + y*y).  Here we see type inference at work because the F# compiler will infer the types of x and y to be integers but will infer from the last statement that diagonal will be of type float.  We may have to come back to let in it’s own post as we’ve really just skimmed over how central it is to the heart of F#.

From an FP perspective, the concept of immutability is critical.  The reason is this, FP is one way to approach the synchronization issues of scaling across multiple computational units (whether those units are clustered computers, distributed computers, multiple processors, or multiple cores on a single processor).  No need for us to get into the issues of threading here but we all know the synchronization issues that arise with shared state.  Immutable data structures solve certain synchronization issues (contention, for example).  If we call the basic unit of computation a thread (or fiber, etc.) then each thread has it’s own immutable copy of the data.  Again, we could have another post strictly about this issue.

More to come

In this post we touched on some of the basic building blocks of FP even if we didn’t really do any FP coding.  We talked about brevity, type inferencing (anonymous types), extension methods, lambda expressions (anonymous methods), pattern matching, tuples, data immutability, and a scattering of syntax facts.  There’s lots more to learn including concepts like; lazy evaluation, deferred execution, aggregation, pure functions, and what functional style programming (known as, declarative) really is.

That just about exhausts what I’ve learned so far.  I appreciate you letting me ramble and dump it all on you.  It’s a great exercise for me.  The next Project Euler problem requires recursion.  Since the principle method of iteration in FP is recursion we’ll have more to talk about.

Tags Tags: , , , ,
Categories: Software Development
Posted By: Carey Cilyok
Last Edit: 26 Mar 2009 @ 02 54 PM

EmailPermalinkComments (3)
 23 Mar 2009 @ 5:14 PM 

I’ve spent today looking at LINQ and F#.    I’m sure I’ll spend quite a bit of the future looking into them.  I’m certainly no clairvoyant or great prognosticator of technology but I do sense a technology shift coming.  It’s the same feeling I got in the late 80’s when object oriented programming began to gain momentum as the way of the future. 

I wish I could write an authoritative technical post on either LINQ or F# but so far the only thing I can say authoritatively is that I have a lot to learn.  I spent most of last week contrasting imperative programming with functional programming and doing searches on “Why should I care about functional programming?“  I decided that if I don’t want to become irrelevant in about 5 years, I’d better get on with learning functional programming techniques.  I only occasionally dabbled in Lisp years ago and trying to capture the functional mindset is proving really difficult for me.

I did use both LINQ and F# to solve the first problem on the Euler Project list.  I’ll post my solutions later once I believe they’re functional solutions instead of imperative; honestly, right now, I’m having trouble knowing the difference.  I’d like to go through the entire list solving all 237 problems in both LINQ and F# but I’m sure my work schedule won’t allow that.  Hopefully, I can work through enough of them that I can get over the hump of thinking like an imperative programmer.  Luckily (or unluckily) F# doesn’t force you into pure functional programming, it tries to ease you into it.

Toss the new features of Enterprise Library 4.1 into the mix and my time looks pretty limited.

No pressure though…  I’m only predicting that I have to change my entire approach to problem solving in order to stay relevant in my chosen profession.

Tags Tags: , , , ,
Categories: Career, Software Development
Posted By: Carey Cilyok
Last Edit: 23 Mar 2009 @ 05 14 PM

EmailPermalinkComments (0)
\/ More Options ...
Change Theme...
  • Users » 258
  • Posts/Pages » 43
  • Comments » 46
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.

Pool Player Vocabulary



    No Child Pages.

Tools



    No Child Pages.