Thursday, February 13, 2014

Haskell Week 3


Functions:

This week I have been focusing on looking at functions in Haskell. Since Haskell is a functional language, functions are unsurprisingly a very important cornerstone of the language. Functions are different in Haskell than in Java, C#, VB and Python. However, in my opinion they are a lot more intuitive and follow a very easy to understand pattern and logic. For example let's take a look at a simple function: the factorial operation.



In Haskell we start by giving the function a name followed by the :: characters and then a definition of the type of parameters that will be given to the function and the type of output that will be returned.

For the above example the function name was "factorial" (very creative I know) and then we used the :: character and defined that the function would take an Integer as a parameter and then return (->) another "Integer".

Once the function is defined we can create an instance of it and assign a variable to represent the Integer parameter, in this case I called it "n". Then I used the built-in product function and said calculate the product of each number starting with number 1 and going through n represented as [1..n].

I enjoy this logic based syntax very much. I think it is not only easier to write but also easier to read and understand. Once the function is defined and then an instance is created we can print out the result, like so:



Once this program is compiled and ran we can see that we get the correct output:

This idea of defining a function will become especially important to me as I begin to work on my Mid-range sorting program.

Stay tuned for more updates on my progress with Haskell!

No comments:

Post a Comment