Haskell程式列印空心直角三角形星號圖案
在Haskell中,我們可以使用replicate函式和遞迴函式來建立空心直角三角形星號圖案。
空心直角三角形星號圖案是由星號(*)組成的圖案,形成一個直角三角形形狀,中間有空隙,如下所示。
** * * * * * * * * * * * * ********
該形狀透過以特定順序列印星號來建立,每行星號的數量隨著行號的增加而增加。
演算法
步驟1 − 使用replicate/遞迴函式定義printRow函式,
步驟2 − 程式執行將從main函式開始。main()函式控制整個程式。它寫成main = do。在main函式中,傳遞一個數字,直到打印出空心直角三角形星號圖案。
步驟3 − 初始化名為“n”的變數。它將儲存要列印空心直角三角形星號圖案的整數。
步驟4 − 函式呼叫後,使用‘putStrLn’語句將結果列印到控制檯。
示例1
在這種方法中,定義了一個名為printPattern的函式,該函式以整數n作為引數,並返回一個表示大小為n的空心直角三角形星號圖案的字串。輔助函式printRow以兩個整數n和i作為引數,並返回一個表示一行星號和空格的字串。printRow函式使用if語句來確定該行是否應填充星號,或者是否應為空心行,兩端為星號,中間為空格。printPattern函式使用列表推導來生成n行星號和空格。
module Main where printRow :: Int -> Int -> String printRow n i = if i == n then replicate i '*' ++ "
" else "*" ++ replicate (i - 1) ' ' ++ "*
" printPattern :: Int -> String printPattern n = concat [printRow n i | i <- [1..n]] main :: IO () main = putStr (printPattern 8)
輸出
** * * * * * * * * * * * * ********
示例2
在此示例中,使用replicate函式定義了該函式以列印空心直角三角形星號圖案。
module Main where printRow :: Int -> Int -> String printRow n i = if i == 1 then "*
" else "*" ++ replicate (2 * i - 3) ' ' ++ "*
" printPattern :: Int -> String printPattern n = concat [printRow n i | i <- [1..n]] main :: IO () main = putStr (printPattern 8)
輸出
* * * * * * * * * * * * * * *
示例3
在這種方法中,printRow是一個遞迴函式,它接受兩個引數n和i,分別表示圖案的大小和當前行。如果i等於1,則返回一個包含單個星號後跟換行符的字串。否則,它返回一個字串,其第一個和最後一個字元為星號,中間部分為等於2 * i - 3的空格數(隨著i的增加,空格數減少),後跟對printRow的遞迴呼叫,其中i - 1作為更新的行號。
module Main where printRow :: Int -> Int -> String printRow n i | i == 1 = "*
" | otherwise = "*" ++ replicate (2 * i - 3) ' ' ++ "*
" ++ printRow n (i - 1) printPattern :: Int -> String printPattern n = printRow n n main :: IO () main = putStr (printPattern 8)
輸出
* * * * * * * * * * * * * * *
結論
在Haskell中,要列印空心直角三角形星號圖案,我們可以使用replicate和遞迴函式。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP