Posts

Showing posts with the label Fibonacci

Adventures in Prolog - Fibonacci

As I have played around with Prolog lately, I wanted to share some enriching moments with my new favourite pet. We start of with the famous Fibonnaci numbers and their computation in Prolog. To spice things up, I used the dynamic clause, which enables one to add clauses to an existing database. :- dynamic (fib/2). fib (0, 1). fib (1, 1). fib (F, X) :- F1 is F-1, F2 is F-2, fib (F1, X1), fib (F2, X2), X is X1 + X2, asserta (fib(F, X)). So what does this listing do? Clearly, it computes the ith value of the Fibonacci sequence using recoursion. Therefore, the recoursion anchor - 1st and 0th value - of the sequence is established first. After that the definition of the sequence is given in its known form. By making the predicate fib/2 dynamic, we can add facts to the list of clauses covering fib/2 . Dynamic has to be executed upon loading the fib database. That is why we write :- dynamic(fib/2). . Now new knowledge about the Fibonnaci values can be added to the database. Th...

Aventures in F# - Fibs

Today's post is about the famous Fibbonaci sequence: 0, 1, 1, 2, 3, 5, 8, ... I will present a recursive and an iterative F# approach to generating the sequence. The Fibbonaci number n = Fib(n) is generated as follows: Fib(n) = Fib(n-2) + Fib(n-1) where Fib(0) = 0 and Fib(1) = 1 The condition Fib(0) and Fib(1) are the anchor to end the recursion and otherwise it is dug into the recursion. Consequently, ... 1. Recursive Approach let rec FibRec n = if n = 0 then 0 else if n = 1 then 1 else (FibRec (n-2) + FibRec(n-1)) ;; As you can see the function is rather straightforward and follows the definition closely. However, its recursive nature make it rather unsuiting for large values of n - you will notice that for large values of n the recursion slows the process down. 2. Iterative approach let FibIt n = if n = 0 then 0 else if n = 1 then 1 else let fibA = Array.create (n+1) 0 fibA.[0] for i = 2 to n do fibA.[i] As you can see the iterative approach employs Fib(0) and Fib...