Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I know there are lots of external packages on linear algebra but my question is really when do I use f# and when c#? I make a simple example and while I did this I realized maybe it is too simple. but lets say I want to do element by element division of two arrays:
Imperative c#:
static double[] elementdivideimp (double[] arr1, double[] arr2)
{
var res = new double[arr1.Length];
for (int i = 0; i < arr1.Length; i++)
{
res[i] = arr2[i]/arr1[i];
}
return res;
}
LINQ c#:
static double[] elementdivideL(double[] arr1, double[] arr2)
{
return arr1.Zip(arr2, (a, b) => b/a).ToArray();
}
f#:
let elementdividefunc a b = Array.map2 (fun i j -> (j / i)) a b
As said maybe this is too simple but I m really struggling to decide which language to go for when I face a programming challenge. SO when do I use which?
As already mentioned in the comments, use the right tool for the job.
Now, the question is, when is F# the right tool for the job. To get a useful answer, it is important to look at the problem from the business perspective - what business problems are you facing and can F# (or any other language) help you solve them?
I think the talk Succeeding with functional-first languages in the industry by Don Syme looks at this problem from the right perspective. It looks at the specific task of developing analytical components and explains what problems people usually face in this domain (correctness, complexity, efficiency and time-to-market) and how better languages can help you overcome those (and many of the points are based on the evidence collected by the F# foundation and numerous earlier SO questions #1 #2).
I think you will not get a clear answer just by comparing fairly simple snippets of code, but your example demonstrates that:
F# code is generally more concise which likely reduces time-to-market
Compared with imperative C#, you do not need to handle corner cases, which aids correctness
You can easily use data structures like arrays, so your code is more efficient (I have not tested this, but I think the C# code uses IEnumerable<T> and will actually be slower in this case).
If you look at other business areas, then you may find different problems and then you can base your evaluation on those. But for analytical components (computations), I think there is a good evidence for languages like F#.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
A few days ago I checked out the C# implementation of Binary Trees test # Computer Language Benchmark Game, and was weirdly surprised: the tree node there is described as a struct (TreeNode) referencing a class (Next) which has two fields of a TreeNode (strut) type. This obviously looks weird, so I updated this code to use a single class (i.e. ~ class TreeNode { TreeNode Left, Right }). My ItemCheck implementation was:
public int ItemCheck()
{
if (ReferenceEquals(Left, null)) // Such a node is always a leaf in this test
return 1;
return 1 + Left.ItemCheck() + Right.ItemCheck();
}
As you may find, it's quite similar to the original implementation. Nevertheless, the performance of this code was ~ 2.2x worse!
Can someone explain why this kind of "optimization" makes sense on .NET? I mostly want to understand what are some other implications of this - of course, if it's not simply a lack in C# / JIT compiler.
A bit more readable version of the same code with a few minor performance improvements can be found here: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/BinaryTrees/Program.cs
Update: I created an extra project for benchmarking this:
Code: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/Benchmarks/Program.cs
Benchmarking results: https://github.com/alexyakunin/BenchmarkGame-CSharp/blob/master/src/Benchmarks/BenchmarkDotNet.Artifacts/results/TreeNodeBenchmark-report-github.md
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For instance, let's say you use fully-qualified namespaces instead of aliases or 'using' statements in an extremely large piece of software. Let's say you type in all kinds of nonsense that doesn't really need to be there, your arrays don't stop iterating when your goal is executed, etc, etc. Would these types of code inefficiencies affect the speed of execution of a piece of software today?
If by 'code bloat' you mean code that is less readable and unnecessarily complex, the main cost of 'code bloat' is longer development time, not slower code. That doesn't mean there's never a cost in terms of efficiency, but sometimes cleaner code is slower. So, I would say that code bloat doesn't necessarily mean the code is slower or faster, except that the unreadability can keep people from coding in performant ways because the hurdle is higher for understanding the code and optimizing for performance.
If by code bloat, you mean algorithmic efficiency, it probably depends on what you are doing. Something that has a performance curve of O(e^n) for large datasets is going to be slow, no matter how fast your processor is. That said, I usually base it on the size of n. If I know my dataset is going to be small (a hard-coded dropdown menu with 7 items), then I won't worry as much if I'm doing a linear search O(n) instead of a binary search in O(log(n)). But I usually tend towards doing it faster if possible.
Big-O-Notation in case I'm speaking greek: https://en.wikipedia.org/wiki/Big_O_notation
Off course number of characters, not even LOC, used in a program doesn't show complexity in general. So we cannot say about it's influence on the total throughput, at least in general terms.
However to be more accurate complexity of your program is really important not today even in the future. Please consider that our needs raise with our abilities. These days we are facing big data, and by this term we mean thousands of terabytes, but about 15 years ago this size of data was unbelievable.
Take a look at these two snippets:
//Block 2 - O(1)
int abcdef1;
int abcdef2;
//...
int abcdef100000;
//----------------
//Block 2 - O(n^2)
for (int i=0; i < n; i++)
for (int j=0; j < n; j++)
//do something
//----------------
it's clear that the number of characters is not a representative measure for complexity.
for more details visit :
Big-O for Eight Year Olds?
http://en.wikipedia.org/wiki/Big_O_notation (as mentioned before)
Do you use Big-O complexity evaluation in the 'real world'?
What is Big O notation? Do you use it?
What is the big deal about Big-O notation in computer science?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Which is best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
As a way to understand the differences between OOP and Procedural languages I was looking for a sample program written in C and C++ or C# or Java. I just want to see the different approaches to the same problem to help me get a sense of the real differences. Does anyone know where I can find a tutorial like this?
I don't think this is likely to teach you much. The program has to have a certain size before the differences between different programming paradigms really show. And people aren't likely to write identical copies if the same program in different languages unless the program is trivial.
Most real-life examples would also be polluted with a lot of extra noise, things that can be done within the standard library of one language, but requires third-party libraries in another. And the programmer who wrote it may be more familiar with one language than another, so his implementation in some languages isn't representative of how it "should" be done.
You're more likely to learn the difference between these paradigms the usual way. By learning what each means, and how to use it.
I recommend the 99 bottles of beer website
You can always look at Project Euler. People solves the same problems in a many different languages. Most people will post their solutions that you can access after you solve the problem also.
Take a look at The Computer Language Benchmarks Game. It's got implementations of various programs in just about every language you could imagine.
This might be a bit simple for your purposes but the Hello World Collection is always fun to look through.
Rosetta Code has a wealth of data but very little of it is related to the procedural/object-oriented distinction. You should also see their collection of related sites.
Black Scholes in multiple languages has plenty of implementations of the Black-Scholes formula.
The formula is implemented in Objective-C/iPhone, F#, Autoit, Fortress, Lua, APL, SAS, Mathcad, J, MEL, Postscript, VB.NET, Clean, Ruby, Lisp, Prolog, PL/SQL, LyME, ColdFusion, K, C#, HP48, Transact SQL, O'Caml, Rebol, Real Basic, Icon, Squeak, Haskell, JAVA , JavaScript, VBA, C++, Perl, Maple, Mathematica, Matlab, S-Plus, IDL, Pascal, Python, Fortran, Scheme, PHP, GNU, gnuplot.
Somebody posted Evil Walrus / ReFactory on Reddit the other day:
http://www.refactory.org/
Here are two programs that implement n-body
Java implementation
C implementation
What differences do you find between them?
Consider the implementation of a snakes and ladders games
In a procedural design we might write a function like
function move(int n) {
pos += n;
switch(pos) {
case 6: pos = 10; break;
case 12: pos = 4; break;
case 15: pos = 32; break;
case 16: pos = 8; break;
// ...
}
}
in an object design language we would create a linked list of Square instances, with some Ladder and Snake instances that branch to other squares.
class Square
def initialize(next)
#tokens = []
#next = next
end
def next(n)
n == 0 ? self : next.next(n-1)
end
def move(token,n)
tokens.remove(token)
target = self.next(n)
target.tokens << token
end
end
class SnakeOrLadder < Square
def initialize(next,branch)
super(next)
#branch = branch
end
def next(n)
# goes to branch when landing on this square!
n == 0 ? #branch : next.next(n-1)
end
end
as you can see, we implement the game rules in the objects as well as the way they are composed (rather than in a switch case statement). This has the advantage that
it is simple to add new game rules at development time, you'll just write a new subclass of Square
it is simple to change the layout of the game at runtime (might sound strange for a game, but for your average business app, this is what you want)
this flexibility is what makes OO so powerful.