Saturday, June 14, 2008

First set of lessons/code

Well, I just wrote a few very simple programs and it's been interesting. I did a "Hello World" in both. D was very easy, however it took a while for me to figure out Haskell as most tutorials are done using an interpreter, which apparently is very different from using a compiler, which is what I was trying to do. I'm personally not liking this aspect of the language because I don't know of any other language that does that. Perhaps it's just the quality of the tutorials, but I think that code written in an interpreter should be identical to what you have to compile using a compiler.

Anyway, I have a factorial program written for each. Well, I have two for Haskell as there are two very different ways according to the one tutorial I was looking at. I'll just show you the cleaner one.

First, D:
import std.stdio; // Module for console IO.

int main(char[][] args)
{
int value = 4;
int factorial = value;
while (--value)
{
factorial *= value;
}
writefln("Result: %d",factorial);
return 0;
}
And now Haskell:

{- Factorial when input == 0 -}
fac 0 = 1

{- Factorial in all other cases -}
fac n = n * fac(n-1)

main = print (fac 42)
Both are very easy to understand and clean. The biggest difference between the two isn't the syntax, but the result. In D, the factorial of 42 was too big for the integer variable to handle, so it kept returning 0. However, Haskell easily printed out what I'm guessing is the correct result. This threw me off because I was expecting to see a similar result from the D version instead of 0.

While I haven't fallen in love with Haskell yet, mainly because it's very different from what I'm used to, I do like the fact that it does that be default instead of requiring an external library that may or may not integrate cleanly with the language. I'll have to read up on it some more, but I think that it'll be nice for applications that need arbitrary-precision math capabilities.

Going back to the syntax, the Haskell one is much easier to read in this case, but this is a basic math problem, so I would expect this. I do know that it'll take me some time to be comfortable with it, but I'm definitely willing to push forward and learn as much as I can stand, especially if I can use it to make reliable apps that don't need C-like speed, but do need something better than Perl.

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home