在这种情况下,如何重复函数?哈斯克尔



我有一个绘制一行字符串的函数和一个绘制字符串框的函数:

duplicate :: [a] -> Int -> [a] -- Duplicates a string/array
duplicate dup n = concat $ replicate n dup
printLine :: String -> Int -> IO () -- Prints a line of strings
printLine str n = putStrLn $ duplicate str n
printBox :: String -> Int -> Int -> IO () -- Prints a box of strings
printBox str width height = putStrLn $ unlines $ replicate height $ duplicate str width
main :: IO ()
main = printBox "-" 10 10 -- Will print 10x10 box of "-" string

我注意到我应该在printBox中使用printLine,因为printLineprintBox功能的一部分。

然而,我尝试了很多次,但都失败了。如何在printBox中使用printLine来达到相同的效果?我应该以某种方式重复一遍吗?

您可以使用Control.Monad中的replicateM_来实现此功能,如下所示:

import Control.Monad
main :: IO ()
main = printBox "-" 10 10 -- Will print 10x10 box of "-" string
duplicate :: [a] -> Int -> [a] -- Duplicates a string/array
duplicate dup n = concat $ replicate n dup
printLine :: String -> Int -> IO () -- Prints a line of strings
printLine str n = putStrLn $ duplicate str n
printBox :: String -> Int -> Int -> IO () -- Prints a box of strings
printBox str width height = replicateM_ height (printLine str width)

该函数有效地复制了您的一元操作n次,并丢弃了结果。文件可以在这里找到

演示

最新更新