Skip to content

Instantly share code, notes, and snippets.

@umairsd umairsd/pascal-triangle.hs
Last active Aug 29, 2015

Embed
What would you like to do?
Pascal's Triangle
-- 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
You can’t perform that action at this time.