Haskell 程式列印菱形星號圖案


在 Haskell 中,要列印菱形星號圖案,我們將使用 mapM_、reverse、unlines 和 replicate 函式。在第一個示例中,我們將使用 (diamondStarPattern n = unlines $ topHalf ++ bottomHalf where topHalf = [replicate (n - i) ' ' ++ replicate ((2 * i) - 1) '*' | i <- [0..n]] and bottomHalf = reverse $ drop 0 topHalf) 函式,在第二個示例中,我們將使用 (diamondStarPattern n = mapM_ putStrLn $ bottomRows ++ topRows where topRows = [spaces i ++ stars (n - 2 * i) | i <- [0..n `div` 2]] and bottomRows = reverse [spaces i ++ stars (n - 2 * i) | i <- [1..n `div` 2]]) 函式。

演算法

  • 步驟 1 − 使用 mapM_ 和 reverse 函式定義 diamondStarPattern 函式

  • 步驟 2 − 程式執行將從 main 函式開始。main() 函式控制整個程式。

  • 步驟 3 − 一旦函式被呼叫並傳入引數,結果的菱形星號圖案就會列印到控制檯。

示例 1

在這個示例中,使用 unlines 和 replicate 函式列印菱形星號圖案。

main = do
  let n = 3
  putStrLn $ diamondStarPattern n

diamondStarPattern :: Int -> String
diamondStarPattern n = unlines $ topHalf ++ bottomHalf
  where topHalf = [replicate (n - i) ' ' ++ replicate ((2 * i) - 1) '*' | i <- [0..n]]
        bottomHalf = reverse $ drop 0 topHalf

輸出

  [1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
   
  *
 ***
*****
*****
 ***
  * 

示例 2

在這個示例中,使用 mapM_ 和 reverse 函式列印菱形星號圖案。

diamondStarPattern :: Int -> IO ()
diamondStarPattern n = mapM_ putStrLn $  bottomRows ++ topRows
  where
    topRows = [spaces i ++ stars (n - 2 * i) | i <- [0..n `div` 2]]
    bottomRows = reverse [spaces i ++ stars (n - 2 * i) | i <- [1..n `div` 2]]
    stars x = replicate x '*'
    spaces x = replicate x ' '

main = diamondStarPattern 7

輸出

  [1 of 1] Compiling Main             ( main.hs, main.o )
Linking main ...
   *
  ***
 *****
*******
 *****
  ***
   *

結論

菱形星號圖案是由星號 (*) 排列成菱形形狀的圖案。該圖案由兩部分組成 - 上三角形和下三角形。上三角形由一系列從中心逐漸縮短的線組成,直到它們在頂部匯聚成一個點。下三角形由一系列從中心逐漸加長的線組成,直到它們在底部達到最大寬度。這兩個三角形由一行星號隔開。整體效果是一個帶有星號圖案的菱形。

更新於: 2023年3月28日

163 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.