简体   繁体   English

在这种情况下如何重复一个功能? 哈斯克尔

[英]How to repeat a function in this case? Haskell

I have a function that draws a line of strings and a function that draws a box of strings: 我有一个绘制一串字符串的函数和一个绘制一串字符串的函数:

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

I noticed that I should use printLine in printBox , because printLine is a part of the functionality of printBox . 我注意到我应该在printBox使用printLine ,因为printLineprintBox功能的printBox

However, I tried many times and failed miserably. 但是,我尝试了很多次,并且悲惨地失败了。 How do I use printLine in printBox to achieve the same effect? 如何在printBox使用printLine来达到同样的效果? Should I somehow repeat it? 我应该以某种方式重复一遍吗?

You can use replicateM_ from Control.Monad to implement this as follows: 您可以使用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)

Effectively the function replicates your monadic action n times and discards the results. 实际上,该函数会复制您的monadic动作n次并丢弃结果。 Documentation can be found here 文档可以在这里找到

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM