Posts
69
Comments
233
Trackbacks
162
Functional Programming with F#/C#
 After all this hype around C# 3.0 where we will get LINQ, lambda expressions and many other thing I thought that it would be useful to have a deeper look at functional programming languages like F#. At Microsoft quite many people are fond of the  Functional Programming style which did influence the design of C# 3.0. Many language architects there have  Haskell background which could explain the renaissance of these "old" concepts. So what's the deal with the functional approach? It does basically force you to think in a twisted way where the problem is straight solved by calling a function which does call another function and so on. Lets assume that you want to get the list of all members of all types which are contained in the assemblies that are currently loaded into your AppDomain (to look at the problem this way is the twisted part) you could write for example (in a functional language like F# this problem is very easy to solve):
// Assign allMembers the result of our "calculation"
let allMembers = System.AppDomain.CurrentDomain.GetAssemblies()
|> Array.to_list |> List.map (fun a -> a.GetTypes()) |> Array.concat
|> Array.to_list |> List.map (fun ty -> ty.GetMembers()) |> Array.concat

// Print them out
do Array.foreach allMembers ( fun memberInfo -> printf "\n%s" memberInfo.Name)
If you want to understand what this little code fragment really does and how it can be rewritten I recommend the post from Robert. A more comprehensible version in C# code would look like this:

        public List<MemberInfo> GetAllMembers()

        {

            Assembly [] allAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            List<Type> allTypes = new List<Type>();

 

            foreach(Assembly assembly in allAssemblies)

            {

                allTypes.AddRange(assembly.GetTypes());

            }

 

            List<MemberInfo> allMembers = new List<MemberInfo>();

            foreach( Type t in allTypes )

            {

                allMembers.AddRange( t.GetMembers() );

            }

 

            return allMembers;

        }

Show more ...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Sunday, May 28, 2006 6:30 PM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *