Programming Praxis – Pascal’s Triangle

In today’s Programming Praxis our task is to neatly display Pascal’s triangle. Let’s get started, shall we?

A quick import to making printing slightly more convenient:

import Text.Printf

Calculating Pascal’s triangle is trivial:

pascal :: [[Integer]]
pascal = iterate (\prev -> 1 : zipWith (+) prev (tail prev) ++ [1]) [1]

To display the triangle correctly, we need to prepend the appropriate amount of spacing to each line based on the longest (i.e. last) line.

prettyPascal :: Int -> IO ()
prettyPascal n = mapM_ (\r -> printf "%*s\n" (div (longest + length r) 2) r) rows
    where rows = map (unwords . map show) $ take (n + 1) pascal
          longest = length $ last rows

An that’s all there is to it. A quick test to see if everything is working proprely:

main :: IO ()
main = prettyPascal 10
About these ads

Tags: , , , , , , ,

One Response to “Programming Praxis – Pascal’s Triangle”

  1. Chris Says:

    Nice to see you back. Learned so much from your answers. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: