Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davejachimiak
Created October 8, 2014 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davejachimiak/e74d69e894ff744099eb to your computer and use it in GitHub Desktop.
Save davejachimiak/e74d69e894ff744099eb to your computer and use it in GitHub Desktop.
-- SICP 1.12
--
-- The following pattern of numbers is called Pascal's triangle.
--
-- 1
-- 1 1
-- 1 2 1
-- 1 3 3 1
-- 1 4 6 4 1
-- ...
--
-- The numbers at the edge of the triangle are all 1, and each
-- number inside the triange is the sum of the two numbers above
-- it. Write a procedure that computes elements of Pascal's
-- triangle by means of a recursive process.
pascalsTriangle :: Integer -> [[Integer]]
pascalsTriangle 1 = [[1]]
pascalsTriangle rowIndex =
let upperTriangle = pascalsTriangle $ rowIndex - 1
upperRow = last upperTriangle
thisRow = 1 : innerRow upperRow [] ++ [1]
in upperTriangle ++ [thisRow]
innerRow :: [Integer] -> [Integer] -> [Integer]
innerRow (_:[]) newRow = newRow
innerRow (x:y:xs) newRow = innerRow (y:xs) (newRow ++ [x + y])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment