Last active
August 29, 2015 14:24
-
-
Save umairsd/e95785e8b3c59e947141 to your computer and use it in GitHub Desktop.
Pascal's Triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Takes an array of integers, and adds pairs of numbers to create a new | |
-- array. For example, [1,2,3,4] changes to [(1+2), (2+3), (3+4)], resulting | |
-- in [3,5,7] | |
sumOfPairs :: [Integer] -> [Integer] | |
sumOfPairs [] = [] | |
sumOfPairs (x:[]) = [] | |
sumOfPairs (x:y:ys) = (x+y) : sumOfPairs (y:ys) | |
-- Given a row of Pascal's triangle, returns the next row | |
next :: [Integer] -> [Integer] | |
next xs = 1 : (sumOfPairs xs) ++ [1] | |
-- Generates the Pascal's triangle. This function generates an | |
-- infinite triangle, so its usage needs to be coupled with the | |
-- take command. For example: take 5 pascalTriangle | |
pascalTriangle :: [[Integer]] | |
pascalTriangle = iterate next [1] | |
-- A: Function that finds the co-efficient of Pascal's Triangle for a given row & column | |
pascal :: Int -> Int -> Int | |
pascal 0 _ = 1 | |
pascal _ 0 = 1 | |
pascal row col | |
| row == col = 1 | |
| col > row = error "Column can't be greater than row" | |
| otherwise = (pascal (row-1) (col-1)) + (pascal (row-1) col) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment