受這個問題的啟發,我制作了這個列印三角形的代碼:
type TriangleMaker = Char -> Int -> [String]
topLeftTriangle :: TriangleMaker
topLeftTriangle c n = [replicate i c | i <- [1 .. n]]
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' replicate i c | i <- [0 .. n]]
getType :: IO TriangleMaker
getType = do
let menu = [topLeftTriangle, centeredTriangle]
putStr $ unlines [
"What type of triangle do you want to print? (type 1 and then type the int size)",
"1) Top Left",
"2) Centered"]
line <- getLine
return (menu !! ((read line :: Int) - 1))
trekant :: IO()
trekant = do
triangle <- getType
size <- getLine
putStr $ unlines $ triangle '*' (read size :: Int)
它在 ghci 中給了我這個輸出:
Ok, one module loaded.
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
1
6
*
**
***
****
*****
******
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
**
***
****
*****
******
我想這樣做,以便我可以使用字串作為輸入而不是字符,如下所示:
trekant :: IO()
trekant = do
triangle <- getType
size <- getLine
putStr $ unlines $ triangle " *" (read size :: Int)
這樣,(我認為)我會得到一個居中的三角形作為輸出:
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
* *
* * *
* * * *
* * * * *
* * * * * *
還是我離這兒很遠?我怎樣才能重寫這個以使三角形居中?
uj5u.com熱心網友回復:
如果你想在中心生成一個三角形,你應該在兩顆星之間添加空格,這意味著字串看起來像:
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' concat (replicate i [c, ' ']) | i <- [0 .. n]]
因此,我們生成一個字串,我們有NI空間,然后?倍的"* "字串。
也許intersperse :: a -> [a] -> [a]在我們'*'用空格散布字符串列的地方作業更優雅:
import Data.List(intersperse)
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' intersperse ' ' (replicate i c) | i <- [0 .. n]]
這將產生:
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
* *
* * *
* * * *
* * * * *
* * * * * *
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316819.html
