You may think that this approach is inefficient, but that’s not true. Here is what the computer does when calculating the call factorial 5: factorial 5 = 5 * factorial 4factorial 4 = 4 * factorial 3factorial 3 = 3 * factorial 2factorial 2 = 2 * factorial 1factorial 1 = 1 * factorial 0factorial 0 = 1 factorial 1 = 1 * 1 = 1factorial 2 = 2 * 1 = 2factorial 3 = 3 * 2 = 6factorial 4 = 4 * 6 = 24factorial 5 = 5 * 24 = 120 For the sake of comprehension, here is an example of a recursive function: factorial :: (Integral a) => a -> afactorial 0 = 1factorial x = x * factorial (x-1) It’s a recursive definition, meaning that the function calls itself. You don’t need them! Those four lines are all it takes in Haskell to calculate the Fibonacci sequence. Haskell version is not optimized at allĪs you can see, the definitions are very similar. Fibonacci sequence as defined in math and Haskell. I’ll explain myself with an example: the Fibonacci sequence. I would also add that Haskell is really like math. ![]() Whatever your function needs is passed as an argument and can be tested. They are black boxes that take input and spit an output without affecting the program in any other way.īonus: This makes testing much easier, because you don’t have some mysterious state that is going to break your function. This means that, in general, functions have no side effects. We also said that Haskell is purely functional. You just enter the function’s name followed by the arguments (as in the terminal, if you please). The code returns the first 10 elements of evenNumbers, so Haskell will only compute those.īonus: as you can see, in Haskell you call a function without parenthesis. ![]() But as we said, Haskell is lazy so it won’t compute anything until forced to do so. This snippet will declare an array containing all the even numbers. At first this may seem strange, but it allows for some pretty nice features - like infinite lists: evenNumbers = Well, lazy means that Haskell will not execute your commands right away, but will wait until you need the result. ![]() ![]() Introductions first: what is Haskell? Haskell is a lazy, purely functional programming language.
0 Comments
Leave a Reply. |