Archive for the 'Func. programming' Category

Foldr in C#

Sunday, February 10th, 2008

Do you know Foldr? Foldr is a function we can find in most of functional programming languages like Haskell (Foldr) or F# (List.Fold_r). It is useful when you need to process all elements in a list and return just one result value (not list), such as ’sum all numbers in a list’.

Foldr is not part of .NET framework, implementation of this function you can find at the end of this article.

Foldr takes list of elements (list), default value (def) which behaves like a last value of the list and function (fun) which is applied to every two adjacent elements.

form:           Foldr ( list, def, fun )

How does it work? Let’s say you need to sum all elements in the list…

Theory

form:           Foldr (  list,                 def,  fun )
code:           Foldr ( { 1,   2,   3,   4 },  0,    + )
execution:                1 + (2 + (3 + (4 +   0)))      = 10

(more…)

TIP! C# 3.0 recursive functions

Sunday, January 27th, 2008

In C# 3.0 there are some new features such as lambda expressions we can find mostly in a functional languages. But when I tried some functional-like possibilities of version 3.0 I was quite dispapointed because I couldn’t declare recursive functions.

So what was the problem? Lets look at this implementation of factorial function int -> int (takes one int and returns int) using C# 3.0 lambda expressions:

Test 1

Func<int, int> fac = x => x == 0 ? 1 : x + fac(x - 1)

This is an optimal solution which unfortunatelly doesn’t work, we get an error message “Use of unassigned local variable ‘fac’“. We can’t use recursive calls like this, because compiler complains that fac is not declared when used.

Test 2
Lets try to declare fac function one line before:

Func<int, int> fac;
fac = x => x == 0 ? 1 : x + fac(x - 1);

Again, same error “Use of unassigned local variable ‘fac’

Test 3

Func<int, int> fac = null;
fac = x => x == 0 ? 1 : x + fac(x - 1);

Now it works! If you want to use recursive calls inside function you have to declare and assign null before body declaration. However here we can see that C# 3.0 doesn’t allow us to write sexy-one-line code like in a first test case.

Haskel and F# comparsion

Sunday, January 6th, 2008

This is quick introduction to F# and its syntax for Haskell programmers. In this article, you can find essential operations written in both Haskell and F#. So if you have already some experience with Haskell then it will be easy to get into the secrets of F#.

Basics, Functions, Lists, Types and some others…

(more…)