
More functional C# - jasallen
I added this code as a comment to a thread that was almost all the way off the front page by the time I got to it.  It was a response to some &#x27;functional folks&#x27; criticizing the verbosity of c#.  While you can certainly do c# the java way, you can also do it in a <i>near</i> functional way.<p>I decided to post the code as a full submission because I think c# often gets dismissed as Java copy-cat, which hasn&#x27;t been true in a decade.<p>The code (non-destructive, no side effects) calculates square roots :<p><pre><code>    public static void Main()
    {
        const int n = 21;

        Observable.Generate&lt;double,double&gt;(1, x=&gt;true, x=&gt; 0.5 * (x + (n&#x2F;x)), x=&gt;x )
        .Scan(new {prv = 0d, cur = 0d}, (prev, curr) =&gt; new {prv = prev.cur, cur = curr})
        .FirstAsync(_ =&gt; Math.Abs(_.cur - _.prv) &lt; 1E-10)
        .Select(_ =&gt; _.cur)
        .Subscribe(Console.WriteLine);

        &#x2F;&#x2F; this is just to compare values, so is not part of the solution
        Console.WriteLine(Math.Sqrt(n)); 
        Console.ReadLine();
    }
</code></pre>
Read the more OO c# implementation that inspired me here:
https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=7044497<p>Read the Haskell code that inspired both here:
https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=7043943
======
profquail
You can write Java code which works similarly to your C# code by using RxJava:
[https://github.com/Netflix/RxJava](https://github.com/Netflix/RxJava)

Or Python, via RxPy: [https://github.com/Reactive-
Extensions/RxPy](https://github.com/Reactive-Extensions/RxPy)

Or JavaScript, via RxJs: [https://github.com/Reactive-
Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS)

Or Ruby, via Rx.rb: [https://github.com/Reactive-
Extensions/Rx.rb](https://github.com/Reactive-Extensions/Rx.rb)

Or Objective-C, via Rx.ObjC: [https://github.com/Reactive-
Extensions/Rx.ObjC](https://github.com/Reactive-Extensions/Rx.ObjC)

Your code is a good demonstration of how Rx works though, and it's nice to
know it's becoming more popular.

~~~
_random_
Rx was invented by Microsoft, so C# is a rightful first choice for Rx examples
:). That code doesn't demonstrate Rx per se, it demonstrates how lambda
expressions, extension methods, anonymous types, type inference enable a
succinct backwards-compatible (to some extent) functional syntax in C#.

~~~
platz
Look at the type signatures of many LINQ and Rx methods. I would hardly say
they are succint. While just using expressions can be compact, maintaining a
functional library or creating functional methods in your application will be
a chore in c# due to the verbosity of the type syntax (Type inference won't
help you on method signatures)

------
Touche
But why do things "near functional" when you have F# which is fully
functional?

~~~
V-2
Because "near functional" is sufficient most of the time and if there is no
compelling reason to split your codebase among two different languages, you
shouldn't do it. Not to mention that there's probably 1000 C# developers for
every F# developer

Have a look at
[http://www.indeed.com/jobanalytics/jobtrends?q=c%23%2C+f%23&...](http://www.indeed.com/jobanalytics/jobtrends?q=c%23%2C+f%23&l=)

And someone has to maintain your near functional or functional code

~~~
altreal
I used to use this argument and only now I realize how flawed it was. At some
point there were 1000 COBOL programmers for every <your favorite language>
programmers. If you decide to go with COBOL career, you will be maintaining
bad software for years.

~~~
jaredsohn
The GP was speaking from the standpoint of the business rather than that of
the developer.

------
Ycros
C#'s functional side is why I actually really enjoy working with it. I get to
use a nice blend of OO and functional, where each makes sense. OO more on a
macro scale, organising code.

~~~
pjmlp
The future is to have multi-paradigm languages.

Each paradigm gets used depending on the type of problem being solved.

~~~
sklivvz1971
Hopefully, the future is having multiparadigm developers. At the moment, most
developers seem to struggle with their first... most of the time without
realizing it.

------
_random_
Maybe it's strange for them to see something that is both functional and
highly practical?

PS: once Roslyn get's finally released, Java will never catch up again.

~~~
altreal
No one is using Java because it has great features compared to C#. Java is
essentially what C# 2.0 used to be and C# has already moved on to V5. People
use Java because it's cross platform. When you write server code you want it
to be able to run on whatever box instead of paying for hefty Windows hosting.
With now Oracle at helm, Java is likely the worst choice for any new project.

------
kevingadd
I'm guessing Observable, Scan, FirstAsync and Subscribe are all from the Rx
reactive/observable framework? I haven't seen them before.

~~~
ppog
Observable, Scan and FirstAsync are from Rx. (FirstAsync is roughly equivalent
to LINQ First(), except that it doesn't block.) This particular Subscribe
method is also part of Rx, but it's basically a helper method around the BCL
System.IObservable<T>.Subscribe(IObserver<T>) that saves you having to
implement IObserver.

------
Pxtl
Absolutely - C# 3.5 introduced a beautiful suite of FP-ish features that made
the language fun to write functional code with, and later versions of C#
parallelized and asynced those FP-ish features.

------
lumpysnake
What's the point of writing code in a functional way to end up with something
that is completely unreadable?

I'd rather have code written in simple, well factored functions and classes
and easy to reason about, than having to deal with such a mess of functional
code.

Don't get me wrong, functional code can be very elegant and clear, but the
example provided here is a huge turn off to me.

~~~
V-2
I don't like the underscore notation (I think it's foreign to C#), but other
than that it's very readable to me, so I guess it's a matter of practice and
(acquired) taste

------
platz
While sprinkling a few expressions like this around is nice, it's quite a
chore to embrace a true dataflow or similiar functionally typed design through
your whole application, because the types in c# are so verbose i.e.

    
    
        public Generate(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector, IScheduler scheduler)

~~~
CmonDev
Methods with that many arguments are probably not a very good idea anyway.

~~~
platz
Unfortunately there's probably not a great alternative in many cases such as
this

------
Dewie
I have read a lot of lang. wars and complaints about programming languages...
but C# is one of the only languages that I can't remember reading any
complaints about. None.

I must conclude, by the usual Stroustrup quote, that no one uses C#. (yes this
is tongue in cheek)

~~~
egeozcan
Well, I use it =) C# is a language with a somewhat limited market
("Enterprise" applications running on Windows Servers, and yes, I know about
Mono). And in this market, a very strict subset of C# (see: Java) is happily
used. I know a lot of people who refrain from using even lambdas and implicit
typing, let alone the other "fringe functional stuff", because "they make
things complicated".

~~~
V-2

       C# is a language with a somewhat limited market 
       ("Enterprise" applications running on Windows Servers,
       and yes, I know about Mono)
    

One would think that Windows Phone - fastest growing smartphone OS - would go
before Mono... geez, I make a living out of desktop C# apps (WPF). Not solely,
but on a daily basis.

~~~
smilliken
Fastest growing is easier to achieve when you have low market share.

Mono is significantly more important for the future of C# than Windows Phone.

~~~
Danieru
You can make it even easier by pretending old versions of your mobile OS don't
count. Or at least it appears you're allowed to do this if you left all your
prior mobile users high & dry after promising them upgrades, twice.

------
kungfooguru
This is a joke, right?

~~~
Chromozon
This is hobbyist code. It should never actually be used out in the real world.
Once you make the distinction, you can better appreciate code snippets like
these.

~~~
geezsaini
If you are going to criticize this approach to C# you are going to need to be
more specific - the classic argument for this kind of thing is correctness,
and against is optimization, is it the latter you are implicitly pointing out?
And if so, what insight as to implementation details that you think make the
solution slower?

