Haskell程式列印映象上三角星形圖案


在本文中,我們將學習如何開發一個Haskell程式,使用mapM函式和unlines函式列印映象上三角星形圖案。映象上三角星形圖案是由星號組成的圖案,形成三角形形狀,三角形的頂端朝上。

以下星形圖案將使您更好地理解映象上三角星形圖案。

    *
   ***
  *****
 *******
*********

該圖案被稱為“映象”,因為三角形的左右兩側是對稱的,形成了映象。

演算法

  • 步驟1 − 我們將從定義一個使用者自定義函式printSpaces開始。

  • 步驟2 − 程式執行將從main函式開始。main()函式控制整個程式。它被寫成main = do。在main函式中,傳遞一個數字,表示要列印映象上三角星形圖案的高度。

  • 步驟3 − 變數“height”被初始化。它將儲存要列印映象上三角星形圖案的整數高度。

  • 步驟4 − 函式呼叫後,使用‘putStrLn’語句將結果列印到控制檯。

示例1

在此示例中,定義了一個函式printMirrorUpperStarTriangle,它接收一個整數n表示三角形的高度,並列印該高度的映象上三角星形圖案。它透過使用mapM_函式迭代數字範圍[1..n]來實現,對於每個數字,它列印適當數量的空格和星號以建立三角形圖案。

module Main where

printSpaces :: Int -> IO ()
printSpaces n = putStr (replicate n ' ')

printStars :: Int -> IO ()
printStars n = putStrLn (replicate n '*')

printMirrorUpperStarTriangle :: Int -> IO ()
printMirrorUpperStarTriangle n = mapM_ (\x -> do
   printSpaces (n - x)
   printStars (2 * x - 1)
   ) [1..n]

main :: IO ()
main = do
   let height = 5
   printMirrorUpperStarTriangle height

輸出

    *
   ***
  *****
 *******
*********

示例2

在此示例中,使用mapM_和replicate函式定義了該函式,以列印映象上三角星形圖案。

module Main where

printLine :: Int -> Int -> IO ()
printLine n x = putStrLn $ (replicate (n - x) ' ') ++ (replicate (2 * x - 1) '*')

printMirrorUpperStarTriangle :: Int -> IO ()
printMirrorUpperStarTriangle n = mapM_ (printLine n) [1..n]

main :: IO ()
main = do
   let height = 5
   printMirrorUpperStarTriangle height

輸出

    *
   ***
  *****
 *******
*********

示例3

在此示例中,定義了一個遞迴函式printMirrorUpperStarTriangle,它接收兩個引數:n和x。n表示三角形的高度,x表示當前行。

module Main where

printSpaces :: Int -> IO ()
printSpaces n = putStr (replicate n ' ')

printStars :: Int -> IO ()
printStars n = putStrLn (replicate n '*')

printMirrorUpperStarTriangle :: Int -> Int -> IO ()
printMirrorUpperStarTriangle n x
   | x > n     = return ()
   | otherwise = do
      printSpaces (n - x)
      printStars (2 * x - 1)
      printMirrorUpperStarTriangle n (x + 1)

main :: IO ()
main = do
   let height = 5
   printMirrorUpperStarTriangle height 1

輸出

    *
   ***
  *****
 *******
*********

結論

在Haskell中,要列印上三角星形圖案,我們可以使用MapM_、replicate或遞迴函式。

更新於: 2023年4月6日

135 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告