in

ExpressionBlog.com

Microsoft Expression Studio Community

This Blog

Syndication

Mirrored Blogs

Browse by Tags

All Tags » C# (RSS)
  • Functional .NET - Fighting Friction in the BCL with Directory.GetFiles

    Very recently on a project, I was having significant issues with System.IO.Directory.GetFiles, in which I was getting an access denied message which prevented further crawling of certain directories.  The performance issue was another issue that was detrimental.  I wasn't happy either with the design of this API.  Instead, I set out to fix some of these issues and come up with a design that I felt better addressed some of my concerns with some techniques from functional programming.   The Issues There are several issues that lead me to come up with an alternative for this situation of getting all files in a directory.  Arrays shouldn't be returned from method calls Processor intensive for iterating over large directory trees instead of calculating only what I need, when I need it Filtering is weak, and only uses file format patterns Access denied internal messages occur for no apparent reason which halts the method Let's talk about each just a little bit more. The first issue with GetFiles is that it returns an array.  Eric Lippert , of the C# team recently posted on "Arrays considered somewhat harmful" , in which he describes that for most cases, arrays should not be used in one form or another.  In this post, he states: You probably should not return an array as the value of a public method or property , particularly when the information content of the array is logically immutable. Let me give you an example of where we got that horridly wrong in a very visible way in the framework.  If you take a look at the documentation for System.Type, you'll find that just looking at the method descriptions gives one a sense of existential dread. One sees a whole lot of sentences like "Returns an array of Type objects that represent the constraints on the current generic type parameter." Almost every method on System.Type returns an array it seems.   Given that the GetFiles method returns an array, we could feel free to mutate the contents of this array and we'd be none the wiser for it.  There is no need, once calculated, to change this value.  This file path is what it is.  If you need to modify the contents, a Map (Select) would do wonders if you are using an IEnumerable<string> instead.  The problem with arrays is that they are a big bucket of mutability.  Coming from the functional programmer standpoint in me, I don't like that as an option, and would rather have an immutable List<T>.  Secondly, there are performance implications of recursing through large directories all at once.  It's very much a blocking call in the application.  Another key point in the functional programming world is to only calculate what you need, aka just-in-time computing.  If I'm not going to immediately use all items in this array, I just calculated all files for no apparent reason.  So, there is a big plus when returning...
  • Functional C# - Implementing Async Computations in C#

    As I covered earlier in my post Functional .NET - LINQ or Language Integrated Monads , I talked about using asynchronous computation expressions (monads) from C# 3.0.  Brian McNamara , of the F# team, posted back in May about using them from C #.  But since then, things have changed slightly.  Before, I showed a basic example of how to utilize the F# libraries from C#, but let's go deep under the covers to see how this actually works.   Getting Started In order to make use of the F# libraries in our C# library, we need to add references to them.  We need the following items: FSharp.Core.dll FSharp.PowerPack.dll FSharp.PowerPack.Linq.dll And then I need to open the namespaces in order to take advantage of F#: using Microsoft.FSharp; using Microsoft.FSharp.Control; using Microsoft.FSharp.Core;   Referencing F# Classes As part of process of creating the asynchronous monad builders in C#, we need to create an instance of the F# class AsyncBuilder in the Microsoft.FSharp.Control namespace.  Unfortunately, the AsyncBuilder has an internal constructor, thus preventing us from creating it directly.  The other option is getting the async instance in the AsyncImpl internal class.  I think the first option is a bit more preferable.  In order to create an instance, all we need to do is invoke the constructor via reflection as a static instance. static   class AsyncExtensions {     public   static AsyncBuilder async = CreateAsyncBuilder();     private   static AsyncBuilder CreateAsyncBuilder()     {         var asyncType = typeof (AsyncBuilder);         var ci = asyncType.GetConstructor(             BindingFlags.Instance | BindingFlags.NonPublic,              null , new Type[ 0 ], null );         var result = ci.Invoke( null );         return result as AsyncBuilder;     } ...   Now that we have this, we have to realize that F# doesn't use the standard .NET delegates for functions.  Let's walk through some ways of converting back and forth.   Converting Functions As we've noted before, F# does not use the standard Func and Action delegates that are commonly used in C# and VB.NET.  Instead, the functions in F# use the FastFunc class.  This allows for the F# compiler to better optimize the closures, especially due to the fact that these closures are quite commonly used.  Another point of difference is that there is no distinction between Func and Action delegates, and instead, for functions that return no value have the return type of Unit.  This is the optimal way of handling this, due to the fact that Void is not treated as a real type, which...
  • Functional .NET - LINQ or Language Integrated Monads?

    As part of my talk at the Richmond Code Camp earlier in October, I had the opportunity to talk about how to implement functional aspects in C# 3.0.  This talk revolved around such concepts as from mutable to immutable, from inheritance to functional composition, and the mind shift that is required.  Part of this discussion involved very briefly a talk about monads.  It's a very misunderstood part of computer science and one of the most powerful concepts to learn.  Much like continuation passing style, this style is often maligned as a result.  But, let's work to change that.   What Is a Monad? Monads come to us originally from category theory.  When monads applied to functional programming, they simply are a construction, given an underlying type system, embeds a corresponding monadic type system.  Simply put, the values you have become amplified values that are to be interpreted by the matching monadic type.  The formulation of a monad comes in three parts: A type construction that defines for every underlying type, how to obtain a corresponding monadic type.  If the given type in F# is 'a, then the corresponding monadic type for an Identity monad would be I<'a>.  I'll cover more of what that means below. A unit function that maps the underlying type to a value in the corresponding monadic type.  In F# parlance, this maps to a Return function. A binding operation of polymorphic type, in F# parlance, (I<'a>) => ('a => I<'b>) => (I<'b>).  This maps to a Bind function given your monad builder.  If you look carefully at the signature of this, you might also note that the LINQ SelectMany follows this syntax.  Gee, what could that mean?  The bind operation follows four steps: The monadic structure exposes the underlying value of type 'a. The given function is applied to the underlying value to obtain values of type I<'b> The monadic structure exposes the underlying value of type 'b. The monadic structure is reassembled over the results, given a single value of type I<'b> Simply put, a monad, unlike your normal function results, stores function results and side-effect representations. This allows side effects to be propagated through the return values of functions without breaking the pure functional model.  This is what makes it so powerful that it is a way to manage side effects.  Given a pure language such as Haskell, this is the way that any side effecting operation should be done.  Granted, there are impure ways of doing IO, but let's not go there. There are some good sources of information on what monads are, including some great stuff from Brian Beckman: Channel9 - Brian Beckman: Monads, Monoids and Mort Channel9 - Brian Beckman: Don't fear the Monads Wes Dyer - Marvel of Monads Some examples of monads that are used frequently are such things as the...
  • Richmond Code Camp 2008.2 - Functional C# Recap

    Thanks to everyone who attended my session "Functional C# or how I lost the foreach and learned to love LINQ".  This is still an ongoing passion of mine that I hope to expand upon in the upcoming posts.  Some of these topics include favoring functional composition over inheritance and implementing patterns such as the Specification Pattern using these techniques.  I'll be posting all code snippets from the functional posts up to date on the MSDN Code Gallery Functional C# Project . Here are some resources that will be helpful in covering functional programming aspects as well as other topics covered: Functional Programming Why Functional Programming Matters - John Hughes Why Haskell Matters F# Home Page C# Futures Is C# Becoming a Functional Language? - Mads Torgersen C# 4.0 : Meet the Design Team Anders Hejlsberg and Guy Steele on Concurrency and Language Design Functional Programming Aspects with C# Functional C# - Into the Great Void Functional C# - Unfolding Lists Functional C# - Learn from F# and LINQ Functional C# - Pattern Matching Recursion in C# Part 1 - Basic Recursion Techniques Part 2 - Recursing into Linear, Tail and Binary Recursion Part 3 - Recursion on Lists Part 4 - Recursing into Recursion - Memoization Part 5 - Continuation Passing Monads The Marvel of Monads - Wes Dyer Don't Fear the Monads - Brian Beckman Monads, Monoids and Mort - Brian Beckman Spec# Spec# Home Page Hanselminutes Episode 110 - Spec# with Rustan Leino and Mike Barnett .NET 3.5, Design by Contract and Spec# Books LINQ in Action Pro LINQ Expert F# Podcasts Software Engineering Radio Episode 108 - Simon Peyton Jones on Functional Programming and Haskell Software Engineering Radio Episode 97 - Anders Hejlsberg Software Engineering Radio Episode 72 - Erik Meijer on LINQ .NET Rocks Episode 310 - Simon Peyton Jones on Functional Programming and Haskell .NET Rocks Episode 270 - Erik Meijer on LINQ As I said before, I'm making the code available as I put it up on MSDN Code Gallery as the FunctionalCSharp project .  This is intended to be a library of functional programming techniques in C# 3.0 and some demonstrations of moving from imperative style programming to a more functional programming style.  This is an ongoing project and more will be added in time, and I may end up just putting them up not as samples, but as a library. Some of the topics covered in these code projects are: Closures Currying Filter High Order Function Fold High Order Function Iterators Lazy Evaluation LINQ Lists (Immutable and Recursive) List Comprehensions Map High Order Function Memoization Monads Operators (Forward, Reverse, etc) Recursion Unfolding and Generators As always, my code snippets can be found on MSDN Code Gallery at the Functional C# Library .
  • Upcoming Events - Richmond, Ruby DCamp and more

    The next couple of months are pretty busy for me.  There are several items worth noting whether I'm speaking or just plain attending.  This is a great season for community events and chances for continuous improvement.   Richmond Code Camp - October 4, 2008 This weekend, I'm going to be attending the Richmond Code Camp in Richmond, Virginia.  I have the privilege of presenting "Approaching Functional Programming in C# or How I Lost the ForEach and Learned to Love LINQ" in which I discuss many of the topics around functional programming aspects while using C#.  This discussion will include functional programming concepts, where C# fits, where it doesn't along with things you need to keep in mind.  Amanda Laucher will also be in attendance presenting some functional programming concepts, so a good time will be had by all. As part of the discussion, my sample code as always is available on MSDN Code Gallery at the Functional C# Project .  I'll post my slides shortly after the discussion as well.  Hope to see a great crowd there.   Ruby DCamp - October 11-12, 2008 Another great event coming to the Washington, DC area is Ruby DCamp.  Up until very recently, many Ruby conferences have followed the traditional paid speaker and audience mold.  Instead, this is an Open Spaces event for Rubyists from all areas to converge on our nation's capital to decide the agenda.  I've found the Ruby community to be filled with some very bright people, especially in the Washington DC area with the DC Ruby Users Group (DCRUG) and Northern Virginia Ruby Users Group (NOVARUG) . RubyDCamp will be held at the Holiday Inn in Arlington, VA.  Best of all, it's metro accessible as well.  Visit RubyDCamp.org for more details.  Register today at Eventbrite !   KaizenConf - October 30 - November 2, 2008 The Continuous Improvement in Software Development Conference will be held at the end of October over Halloween and into early November.  This looks to be a great event for sharing ideas on how we advance our craft through continuous improvement.  I will be leading a workshop on Functional Programming Concepts and more in particular F#. But, what is it all about anyways?  Some of the questions that we need to consider are: How do we improve? How do we recognize new improvements? What improvements in the past led us to where we are now? How do we decide which improvements to make? What values drive our decisions for improvement? What improvements can we be making right now? What obstructions impede improvement? What improvements are on the horizon? How can we adapt easier to the changes that improvements bring? What are the practices and processes that enable improvement? Getting to share ideas on continuous improvement are quite important to me, and getting to share them with the likes of Mary and Tom Poppendieck will be wonderful.   QCon San Francisco...
  • Emulating Java Enums in .NET - F# Edition

    I'm not usually one to follow up replies from another's blog in my own, but some challenges need further analysis.  Ayende posted earlier about emulating the behavior of Java Enums in .NET .  Since the inception of C#, there has been a lot of back and forth between Java and C# in terms of features such as generics, attributes (annotations), foreach statements, and lastly enums.  There are significant differences between the two, but let's see if we can bridge that gap.   Enter Java Enums Previous to Java 5.0, Java had a standard way of delcaring an enumerated type as a constant.  This was neither type safe, brittle and rather uninformative (what does 3 mean anyways?).  Finally, come 5.0, this feature was added to have simple enums such as we've had in C# all along.  But, unlike C#, these were not capable of being cast to an integer, unsigned or otherwise.  A simple enum could look something like this. public enum PriorityLevel { Low, Medium, High }   Not only can they hold the value just as C/C++/C# enums can, they can also hold behavior and data.  Let's expand our PriorityLevel to hold an integer level equivalent. public final enum PriorityLevel { Low( "Low Priority" ), Medium( "Medium Priority" ), High( "High Priority" ); private static final Map<String,Status> lookup = getLookup(); private static HashMap<String, PriorityLevel> getLookup() { HashMap<String, PriorityLevel> l = new HashMap<String,PriorityLevel>(); for (PriorityLevel p : EnumSet.allOf(PriorityLevel. class )) l.put(p.getLevel(), p); return l; } private String level; private PriorityLevel(String level) { this .level = level; } public String getLevel() { return level; } public static PriorityLevel get(String level) { return lookup.get(level); } }   This gives us the ability to define a string equivalent for our given enum value.  This can be a powerful concept that the data is not just limited to integers.  So, this had me thinking about the possibilities of this in .NET.   Enter C# 3.0 and Extension Methods Given that the ability of the Java enum has the ability to map itself to another data type's equivalent quite easily, it was a matter of time before we tried something like that in C#.  With the birth of extension methods, we have the ability to add features onto given types, such as enums.  An example of taking the above example and using extension methods might look like this. public   enum PriorityLevel {     Low,     Medium,     High } public   static   class Extensions {     public   static   string GetLevel( this PriorityLevel level)     {         switch (level)         {             case PriorityLevel...
  • Herding Code Episode 18 - Functional Programming and F#

    A couple of days ago, I had the pleasure of recording Episode 18 of Herding Code on Functional Programming and F#.   The topic on their minds was around functional programming, and more in particular with some of the things I've been doing around the .NET space both C# and F#.  Some of the things I talked about in this episode were around the following topics: What is Functional Programming and why should we care? C# and the evolution of the language with functional aspects and where it falls short What is F# and what is the value proposition? Some of the uses of F# I had a lot of fun doing this episode and I hope it shows!  Feedback is always appreciated.
  • Functional C# - Pattern Matching

    In the past, I've covered quite a bit of functional programming in C# 3.0 and how you can implement some of the basic constructs using the language.  In preparation for the Richmond Code Camp coming up on October 4th, for which I'm planning to present "Functional C# -or- How I lost the foreach and learned to love LINQ", I'm revisiting some of the topics I've talked about in the past.  One of those topics is pattern matching . Pattern Matching Earlier in my introduction to F# series, I covered pattern matching and how clear and concise it can make your programs.  You can more program to your intent instead of needing to switch between if statements, case statements and so on.  Basically, pattern matching is the way of checking for conditions on a given parameter with rigid specifications.  Pattern matching is a strongly functional programming concept and is present in F#, OCaml, Haskell, Erlang, etc.  Erlang is an interesting one here as you can define the patterns, which in turn will define the type.  As Erlang is a dynamic language, you do not need to specify the type beforehand, so implementing patterns then define that type. Pattern matching in F# is pretty flexible as it allows to match against explicit values, structures, lists, guarded ranges, .NET types, active patterns and so on.  The basic syntax is match ... with ... expressions such as this. match expression with | pattern_1 -> expression_1 | pattern_2 -> expression_2 | pattern_n -> expression_n   Similarly, I could use the function keyword should I create a function with the parameter to pattern match against instead of the above syntax, such as this. let get_value = function   | None ->   0   | Some n -> n let value = get_value ( Some 25 ) As you may notice, F# has very flexible syntax for describing these, so let's look at a few more ideas before we move on. Data Structure Matching We can pattern match against data structures, such as lists quite easily.  Lists are a special case as it allows you to match against the head and the tail of the given list.  By using the head::tail notation allows us to specify that we will receive the head and tail values should they be present.  Such an example might be to get the evens from a given list. #light let   rec even_list = function   |   [ ]   ->   [ ]   | h : : t when h % 2 = 0   -> h : : even_list t   | h : : t -> even_list t let evens = [ 1 . .20 ]   | > even_list   Active Patterns Pattern matching in F# is extremely flexible, as you can extend what you can pattern match.  Through a mechanism called "Active Patterns", you can extend the syntax quite easily.  Let's say for instance that we want to create a pattern to determine whether a given number is either a composite number, prime number or neither.  We can define a pattern over...
  • Side Effects and Functional Programming

    One of my first posts at CodeBetter was in regards to side effects and how, when unmanaged, can be truly evil.  Today, I want to revisit that topic briefly in regards to functional programming and managing side effects.  When I was out in Redmond a couple of months ago, I had the opportunity to sit down with Erik Meijer to discuss functional programming among other topics.  In there, we discussed a number of issues around managing side effects and state in your code, and how both C# and F# don't intrinsically support such a concept.  Languages like Haskell, of course do with IO monads and other such monadic structures.  Whether languages such as F# and Erlang are hoaxes as functional programming languages is another matter, due to the fact that you don't have to declare when you are side effecting (reading a database, writing to console, spawning a process, etc).  Erik recently gave a talk called "Fundamentalist Functional Programming" in which he is not shy about his beliefs that nirvana lies in a more functional style, and side effects are declared and managed.  In this post, I want to go over just a few of the ideas expressed, because I'm wholly on board with this notion.  The Problem of Purity In some previous posts, I talked about function purity in regards to things you should keep in mind with a functional mindset.  In order to qualify as such, you need to meet the following criteria: Evaluate with the same result given the same input, and perform no state change. Evaluation of the given function does not cause observable side effects (write to console, write to database, etc) Things get even more clouded as we bring lazy evaluation to the table.  One of the great things that came to C# in 2.0 and especially in 3.0 with LINQ was the idea of lazy evaluation through the yield keyword.  This gave us the ability to defer work until it was absolutely needed.  That's one of the hallmarks of functional programming, especially a lazy language such as Haskell. Let's look at a code snippet both written in F# and the equivalent in C# and let's determine the order of side effects.  Can they be predicted here?  When do the side effects happen?  Do I just get a nice list of my integers at the end? F# #light let divisible_by_two n =    printf "%i divisible by two?" n   n % 2 = 0 let divisible_by_three n =   printf "%i divisible by three?" n   n % 3 = 0    let c1 = { 1   . .   100 }   | > Seq . filter divisible_by_two let c2 = c1 | > Seq . filter divisible_by_three c2 | > Seq . iter ( fun c -> printfn "%i" c ) C# static   bool DivisibleByTwo( int n) {     Console.Write( "{0} divisible by 2?" , n);     return n % 2 == 0 ; } static   bool DivisibleByThree( int n) {     Console.Write( "{0} divisible...
  • How do I Write that In JavaScript?

    A comment was left in response to Master Detail in Silverlight 2 asking " Any hint how to create such a sample with Java Script instead C# ?" I thought the answer was important enough to post to the blog in general... Two points about your question. The first is whether you are asking if one can write this same program in JavaScript in Silverlight 2 (answer: yes) or you are asking if one can write the same program in Silverlight 1.0 (which only uses Javascript) (answer: depends). Second point is that there are a number of languages that SL2 supports: IronRuby, JavaScript, VB, C#, etc., and (frankly) it won't be possible for me to illustrate all of them (or even most of them) in these examples, but it shouldn't be terribly hard to translate the logic from one language to another because the code is pretty simple and the Silverlight documentation shows the syntax for each event, method and property in the various languages. While it is true that Silverlight 2 supports JavaScript, it is also true that C# supports language features that simply are not available in Javascript such as generics (ListOf<Books>) and true classes and objects. Translating my examples from C# to (e.g.,) VB is trivial, but translating to JavaScript is more of a challenge. Which brings me to my final point, which is that I honestly can't imagine why you'd want to do this in Javascript; the code will be slower, harder to maintain and harder to create. If you'll pardon what may sound rude and even arrogant, I think you'll be a lot happier if you take the opportunity to "step up" to managed code (see, for example, Programming C# 3.0, 5th Edition by my favorite author) which will not only enhance your Silverlight experience, but will bring you nicely into the entire spectrum of .NET programming from ASP.NET, ASP.NET/AJAX through WPF, WCF, Workflow, etc. Programming C# 3.0 (Programming) by Jesse Liberty, Donald Xie Read more about this title... You'll love it. I tried it in 2000 and never looked back.
Powered by Community Server (Commercial Edition), by Telligent Systems