haskell - 从带有文本的列表中打印数字

时间:2016-05-04 19:58:37

标签: haskell

我正在尝试编写一个接收数字的函数,并打印此文本,例如elephants 5打印以下内容:

If 2 elephants bother a lot of people, 3 elephants bother a lot more!
If 3 elephants bother a lot of people, 4 elephants bother a lot more!
If 4 elephants bother a lot of people, 5 elephants bother a lot more!

从1或2开始,以我给出的数字结束。 我这样做了:

module Main where
import Control.Monad  

elephants n = 
    if ( n`mod`2 ==0 ) then do   
    colors <- forM [1,3..n] (\a -> do  
        putStrLn $ "If " ++ show a++ " elephants bother a lot of people,\n"++ show (a+1)++ " elephants bother a lot more!" 

        )  
    putStr "" 
    else do
    colors <- forM [2,4..(n-1)] (\a -> do  
        putStrLn $ "If " ++ show a++ " elephants bother a lot of people,\n"++ show (a+1)++ " elephants bother a lot more!" 

        )  
    putStr"" 

它打印以下内容:

> elephants 5
If 2 elephants bother a lot of people,
3 elephants bother a lot more!
If 4 elephants bother a lot of people,
5 elephants bother a lot more!

我写colors <- forM [1,3..n]的部分,颜色不代表任何东西,只是程序运行。我知道这可能不是正确的方法;怎么可以改进?

1 个答案:

答案 0 :(得分:1)

  

我写colors <- forM [1,3..n]的部分,颜色不代表任何东西,它只是让程序运作。

但这确实意味着什么,它意味着大约&#34;从1到n的预期值,按2(3-1)计算这个monadic动作&#34;。

显而易见的变化是计算1和3或2和4并在单一的monadic事件中使用它们,但从根本上说你不会在那里做错误的工作。