views:

198

answers:

3

I know that in C# 3.0 you can do some functional programming magic with Linq and lambda expression and all that stuff. However, is it really possible to go completely "pure" functional in C#? By "pure" I mean having methods that are pure (always gives the same output for the same input) and completely free of side-effects. How do we get around the fact that we do not even have immutable integer type in C#?

+2  A: 

Have you looked into F#? It seems much more along the lines of what you are talking about. C# just really isn't designed with functional programming in mind, and therefore won't really give you any of the benefits that are normally associated with a functional language.

Toji
I'm quite familiar with F# actually, however I still love C# because it kinda allows me to get the best of both worlds. But I guess that sort of contradicts my question huh... LOL.
Hao Wooi Lim
Wierd, I see F# as allowing the best of both worlds. C#'s too verbose to be of much use when doing functional programming.
MichaelGG
+3  A: 

If you want to program in a pure functional way, there is nothing stopping you.

On the other hand, if you have some program, there is no magic flag you can flip to force the program to behave in a pure functional way.

For ints (immutable)

  • If you use an int as a parameter, it is passed by value. Any changes are not propogated to the caller.
  • If you use an int declared in one method's scope in a closure within the method, than that int variable is shared. In this case, one must either pledge not to modify the int (programmer enforced), or simply not use an int in this way.

And if you truly need an immutable int, have you seen the readonly keyword?

David B
+1  A: 

Unfortunately no - C# is not a pure functional language and it does not intend to be. What has happened is that the C# team has seen that there are benefits to adding certain functionally-styled constructs and syntax to the language.

Functional purity is better found in other places (Lisp derivatives like Common Lisp and Scheme are good places to start).

Andrew Hare
Lisp and Scheme are not pure functional languages either.
MichaelGG