Tuesday, December 11, 2012

Functional Fibonaccis in Haskell

Lately, I've been learning my first functional programming language: Haskell. Thus far, it is truly awesome! Look at the following Fibonacci function (I know it's a dead-horse example):

nthFib :: (Integral a) => a -> a
nthFib 1 = 1
nthFib 2 = 1
nthFib n = nthFib (n-1) + nthFib (n-2) 


So, "What makes this simple Fibonacci example so awesome?" you may ask. Well, there are a few things I really like about it, but the main thing is that it actually looks like the mathematical definition for the Fibonacci Series! Also, that first line looks a lot like "nthFib: Z -> Z", you know, that good-old-mathy notation meaning, "nthFib is a function that maps an integer to an integer" (I know, I know, the first 'a' should be a natural number, I'm still getting there). But this is wicked stuff!


No comments:

Post a Comment