Skip to content

Instantly share code, notes, and snippets.

@linse
Created February 23, 2014 06:07
Show Gist options
  • Save linse/9167708 to your computer and use it in GitHub Desktop.
Save linse/9167708 to your computer and use it in GitHub Desktop.
Print the Sierpinski and Pascal triangle in Haskell
instance Num a => Num [a] where -- (1)
(f:fs) + (g:gs) = f+g : fs+gs -- (2)
fs + [] = fs -- (3a)
[] + gs = gs -- (3b)
(f:fs) * (g:gs) = f*g : [f]*gs + fs*(g:gs) -- (4)
_ * _ = [] -- (5)
abs = undefined -- I can't think of a sensible definition
signum = map signum
fromInteger n = [fromInteger n]
negate = map (\x -> -x)
pascal = map ([1,1]^) [0..]
sierpinski = map (map (\a -> a `mod` 2)) pascal
printTri n t = zipWith (\a b -> a++show b) paddings t'
where t' = take n t
paddings = map (flip replicate ' ') offset
offset = map (maxwidth `div` 2 -) widths
widths = map (flip div 2.length.show) t'
maxwidth = length.show.last $ t'
-- todo: why is the offset still off?
printPascal = mapM_ (putStrLn.show) (printTri 20 pascal)
printSierpinski = mapM_ (putStrLn.show) (printTri 20 sierpinski)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment