将输入作为字符串,并使用do-notation打印10次?
print10Times :: String -> IO ()
print10Times name = putStrLn $ repeat 10 name
main :: IO ()
main = do
putStrLn "What is your name?"
name <- getLine
print10Times name发布于 2016-06-07 22:38:47
您可以使用replicateM_来实现这一点。
Λ: :t replicateM_
replicateM_ :: Monad m => Int -> m a -> m ()
Λ: do { putStrLn "what is your name?" ; name <- getLine ; replicateM_ 10 (putStrLn name) }
what is your name?
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business
none of your business发布于 2016-06-07 22:21:21
repeat只接受一个参数,并且无限地重复它。您可能正在寻找take 10 $ repeat name。
如果要打印列表,最好使用mapM_将putStrLn映射到列表中的每个元素。试试这个:
print10Times :: String -> IO ()
print10Times name = mapM_ putStrLn $ take 10 $ repeat name或者,更简洁地说:
print10Times = mapM_ putStrLn . take 10 . repeat发布于 2016-06-08 00:01:57
您绝对可以像@pdexter建议的那样使用replicateM_,也可以使用递归重写它:
print10Times :: String -> IO ()
print10Times = printNTimes 10
printNTimes :: Int -> String -> IO ()
printNTimes n name | n <= 0 = return ()
| otherwise = do
putStrLn name
printNTimes (n-1) name
main :: IO ()
main = do
putStrLn "What is your name?"
name <- getLine
print10Times nameprint10Times只是用一个常量10 (应该打印的次数)将控制重定向到printNTimes。然后,每次打印名称时都会执行减量,如果计数器命中0,则执行return ()。
这是对replicateM_的一种重塑,可以定义为:
replicateM_ :: (Monad m, Num n, Ord n) => n -> m a -> m ()
replicateM_ n f = loop n
where loop i | i <= 0 = return ()
| otherwise = f >> loop (i-1)https://stackoverflow.com/questions/37681485
复制相似问题