Functions and Fractals: Sierpinski triangles

  • + 0 comments

    My recursion solution in Haskell:

    main :: IO ()
    main = readLn >>= putStr . unlines . sierpinski 32 63
    
    sierpinski :: Int -> Int -> Int -> [String]
    sierpinski _ m 0 = f <$> [1,3..m]
      where
        f i = zeroes ++ (replicate i '1') ++ zeroes
          where zeroes = replicate ((m - i) `div` 2) '_'
    
    sierpinski n m i = (zeroes `comb` smaller `comb` zeroes)
      ++ (smaller `comb` column `comb` smaller)
      where
        m' = m `div` 2
        n' = n `div` 2
        smaller = sierpinski n' m' (i - 1)
        zeroes = replicate n' $ replicate ((m - m') `div` 2) '_'
        column = replicate n' "_"
        comb = zipWith (++)