受这个问题的启发,我编写了这段代码来打印出三角形:
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
*
* *
* * *
* * * *
* * * * *
* * * * * *
还是我离这儿很远?我怎样才能重新编写它以使三角形居中?