# Haskell Quiz/PP Pascal/Solution Burton

(Difference between revisions)
Jump to: navigation, search

```{--
*Main> ppPascal 10
1
1     1
1     2     1
1     3     3     1
1     4     6     4     1
1     5     10    10    5     1
1     6     15    20    15    6     1
1     7     21    35    35    21    7     1
1     8     28    56    70    56    28    8     1
1     9     36    84    126   126   84    36    9     1

--}
--Pascal's triangle from http://www.haskell.org/haskellwiki/Blow_your_mind
pascal :: [[Integer]]
pascal = iterate (\row -> zipWith (+) ([0] ++ row) (row ++ [0])) [1]

ppPascal :: Int -> IO ()
ppPascal n = mapM_ (putStrLn . ppRow) tr
where tr     = take n pascal
mRow   = last tr
pad    = cols \$ maximum \$ mRow
cols n = if n < 10 then 1 else 1 + cols (n `div` 10)
ppRow r@(x:xs) = padRow ++ (showFirst x)
++ (concatMap showRest xs) ++ padRow
where showFirst e = (show e) ++ (padR e)
showRest  e = padL ++ (show e) ++ padR e
padRow      = replicate ((length mRow - length r)*pad) ' '
padL        = replicate pad ' '
padR d      = replicate (pad-(cols d)) ' '```

A bit shorter than the above, though certainly not prettier. (reverse._.reverse) makes it easier to calculate the leading padding for each line. -- AlsonKemp

```pascal :: [[Integer]]
pascal = iterate (\row -> zipWith (+) ([0] ++ row) (row ++ [0])) [1]

ppPascal :: Int -> IO ()
ppPascal n = mapM_ putStrLn \$ reverse \$ ppRow 0 (reverse tr)
where ppRow _     []     = []
ppRow lpads (x:xs) = (replicate lpads ' ' ++ concatMap (padNum pad) x) : (ppRow (lpads+pad) xs)
tr            = take n pascal
padNum pads n = take (2*pads) (show n ++ (repeat ' '))
pad           = 1 + (length \$ show \$ maximum \$ last tr) `div` 2```
{"extraction_info": {"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.9874252676963806, "perplexity": 18921.20848427107}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": false}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2015-32/segments/1438042990900.28/warc/CC-MAIN-20150728002310-00295-ip-10-236-191-2.ec2.internal.warc.gz"}