ピラミッドを作る

どう書く?org - ピラミッドを作る

与えられた高さのピラミッドを作る

 module Main where
 
 
 import System
 
 
 cjust :: Int -> String -> String
 cjust w s | w <= length s = s
           | otherwise     = margin ++ s ++ margin
   where
     margin = replicate ((w - (length s)) `div` 2) ' '
 
 pyramid :: [String]
 pyramid = map (flip replicate '*') [1,3..]
 
 main :: IO ()
 main = do h <- getArgs >>= return.read.head
           putStr $ unlines $ map (cjust (h*2-1)) $ take h pyramid

実行。

 ^o^ >runhaskell pyramid.hs 4
    *
   ***
  *****
 *******
 
 ^o^ >runhaskell pyramid.hs 5
     *
    ***
   *****
  *******
 *********
 
 ^o^ >runhaskell pyramid.hs 6
      *
     ***
    *****
   *******
  *********
 ***********
 
 ^o^ >runhaskell pyramid.hs 1
 *
 
 ^o^ >runhaskell pyramid.hs 0

お,高さ0でもちゃんと動く。