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 ... * *** ***** ******* ***** *** *
结论
菱形星号图案是由星号 (*) 排列成菱形形状的图案。该图案由两部分组成 - 上三角形和下三角形。上三角形由一系列从中心逐渐缩短的线组成,直到它们在顶部汇聚成一个点。下三角形由一系列从中心逐渐加长的线组成,直到它们在底部达到最大宽度。这两个三角形由一行星号隔开。整体效果是一个带有星号图案的菱形。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP