0

这个问题的启发,我编写了这段代码来打印出三角形:

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

      * 
     * *
    * * *
   * * * *
  * * * * *
 * * * * * *

还是我离这儿很远?我怎样才能重新编写它以使三角形居中?

4

1 回答 1

1

如果你想在中心生成一个三角形,你应该在两颗星之间添加空格,这意味着字符串看起来像:

centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' ++ concat (replicate i [c, ' ']) | i <- [0 .. n]]

因此,我们生成了一个字符串,其中我们有ni个空格,后跟n"* "字符串。

也许在我们用空格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
          
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *
于 2021-10-10T15:44:36.480 回答