Skip to content

Instantly share code, notes, and snippets.

@Ino4137
Forked from Xophmeister/sierpinski.hs
Last active April 25, 2018 13:18
Show Gist options
  • Select an option

  • Save Ino4137/e6e5c9597e51f45be949f4363c8dd5e2 to your computer and use it in GitHub Desktop.

Select an option

Save Ino4137/e6e5c9597e51f45be949f4363c8dd5e2 to your computer and use it in GitHub Desktop.
Sierpinski Triangle in Haskell
sumPairs :: [Integer] -> [Integer]
sumPairs (x:y:s) = (x + y) : sumPairs (y:s)
sumPairs _ = []
pascal :: Integer -> [Integer]
pascal 0 = [1]
pascal n = sumPairs $ 0 : pascal (n - 1) ++ [0]
sierpinski :: Integer -> String
sierpinski n = pascal n >>= (ascii . odd)
where
ascii True = "##"
ascii False = " "
sierpinskiTriangle :: Integer -> [String]
sierpinskiTriangle n = map (centre . sierpinski) [0..n]
where
centre line = (spaces $ 1 + fromIntegral n - length line `div` 2) ++ line
spaces = flip replicate ' '
main :: IO ()
main = putStr . unlines $ sierpinskiTriangle 63
##
####
## ##
########
## ##
#### ####
## ## ## ##
################
## ##
#### ####
## ## ## ##
######## ########
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
################################
## ##
#### ####
## ## ## ##
######## ########
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
################ ################
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
######## ######## ######## ########
## ## ## ## ## ## ## ##
#### #### #### #### #### #### #### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
################################################################
## ##
#### ####
## ## ## ##
######## ########
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
################ ################
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
######## ######## ######## ########
## ## ## ## ## ## ## ##
#### #### #### #### #### #### #### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
################################ ################################
## ## ## ##
#### #### #### ####
## ## ## ## ## ## ## ##
######## ######## ######## ########
## ## ## ## ## ## ## ##
#### #### #### #### #### #### #### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
################ ################ ################ ################
## ## ## ## ## ## ## ##
#### #### #### #### #### #### #### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
######## ######## ######## ######## ######## ######## ######## ########
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#### #### #### #### #### #### #### #### #### #### #### #### #### #### #### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
################################################################################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment