Showing posts with label Haskell. Show all posts
Showing posts with label Haskell. Show all posts

Saturday, November 14, 2009

Greatest Common Divisor and Least Common Multiple functions in Haskell

Recently, I wrote a post about finding the gcd and lcm with C: http://knowledge-aholic.blogspot.com/2009/11/greatest-common-divisor-and-least.html

Since then, I have started Haskell and here is how implemented the "same" functions with Haskell (note that with Haskell, I have to use recursion to find the gcd) :


mygcd :: Int -> Int -> Int
mygcd n m
 | m == 0 = n
 | otherwise = mygcd m (mod n m)
 
mylcm :: Int -> Int -> Int
mylcm n m = div (n * m) (mygcd n m) 

Wednesday, November 11, 2009

An elegant Fibonacci solution with Haskell

Here's a very elegant Fibonacci solution I found in Simon Thompson's book, The Craft of Functional Programming:

--Given a tuple with a fibonacci pair, this function returns another tuple with
--the next two numbers in the sequence
fibStep :: (Int, Int) -> (Int, Int)
fibStep (u,v) = (v, u + v)

--The Definition for the Fibonacci pair
fibPair :: Int -> (Int, Int)
fibPair n
| n == 0 = (0,1)
| otherwise = fibStep (fibPair (n - 1))

--Pass the output of the fibPair function to Haskell's fst function,
--which returns the first item in the given tuple
fastFib :: Int -> Int
fastFib = fst . fibPair