我試圖理解為什麼我的代碼不起作用:
writeRow :: Int -> IO()
writeRow x = putStr(concat (replicate x "* "))
triangle :: Int -> IO()
triangle x = do
writeRow x
putStr ""
triangle x-1
我的想法是,writeRow 創建一行 x 乘以“*”,所以如果 x = 4,三角形 4 會寫
* * * *
由於三角形以 x -1 遞歸調用,因此下一行將是:
* * *
依此類推……直到:
* * * *
* * *
* *
*
但它只是在一行上輸出所有內容:
* * * * * * * *
似乎是什麼問題?:D
putStr
只打印字符串,不寫新行,你應該使用putStrLn
. 此外,您應該triangle (x-1)
在x-1
零件周圍使用括號,並為三角形的遞歸指定基本情況:
writeRow :: Int -> IO()
writeRow x = putStr(concat (replicate x "* "))
triangle :: Int -> IO()
triangle x | x <= 0 = pure ()
triangle x = do
writeRow x
putStrLn ""
triangle (x-1)
通過這些修改,我們得到:
Prelude> triangle 4
* * * *
* * *
* *
*
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句