【问题标题】:Center a triangle (HASKELL)使三角形居中(HASKELL)
【发布时间】:2021-11-29 15:18:59
【问题描述】:

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

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

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

【问题讨论】:

  • 提示:星星之间有空格。
  • 所以我应该在最后一行做类似putStr $ unlines $ intersperse ' ' $ triangle '*' (read size :: Int) 之类的操作,而不是更改类型?

标签: haskell ghci triangle


【解决方案1】:

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

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

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

也许使用intersperse :: a -&gt; [a] -&gt; [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
          
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多