居中三角形 (HASKELL)

Center a triangle (HASKELL)

受到this问题的启发,我制作了这段打印出三角形的代码:

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

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

或者我离这里太远了?我怎样才能重写它以使三角形居中?

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

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

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

也许使用 intersperse :: a -> [a] -> [a] 更优雅,我们用空格穿插 '*' 个字符的列表:

import Data.List(intersperse)

centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' ++ <strong>intersperse ' ' (replicate i c)</strong> | 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
          
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *