claudia
claudia

Reputation: 33

haskell - print numbers from a list with text

I was trying to write a function that receives a number, and prints this text, for example, elephants 5 prints the following:

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!

It starts by 1 or 2, and ends at the number that I gave. I have done this:

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"" 

It prints the following:

> 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!

The part where I wrote colors <- forM [1,3..n], the colors dont mean anything, it is just for the program to function. I know that this probably isn't the right way to do this; how could it be improved?

Upvotes: 1

Views: 272

Answers (1)

Guvante
Guvante

Reputation: 19203

The part where I wrote colors <- forM [1,3..n], the colors dont mean anything, it is just for the program to function.

But that does mean something, it means roughly "foreach value from 1 to n counting by 2 (3-1) do this monadic action".

The obvious change would be to calculate 1 and 3 or 2 and 4 and use them in a single monadic event but fundamentally you aren't doing incorrect work there.

Upvotes: 1

Related Questions