/ / haskell - wypisuje numery z listy z tekstem - haskell

haskell - drukuj numery z listy z tekstem - haskell

Próbowałem napisać funkcję, która odbiera liczbę i wypisuje ten tekst, na przykład elephants 5 drukuje następujące informacje:

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!

Zaczyna się od 1 lub 2 i kończy na podanym przeze mnie numerze. Ja to zrobiłem:

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

Wyświetla następujące informacje:

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

Część, w której napisałem colors <- forM [1,3..n], kolory nic nie znaczą, tylko dla programu do działania. Wiem, że to prawdopodobnie nie jest właściwy sposób, aby to zrobić; jak można to poprawić?

Odpowiedzi:

1 dla odpowiedzi № 1

Część, w której napisałem colors <- forM [1,3..n], kolory nic nie znaczą, tylko dla programu do działania.

Ale to coś znaczy, oznacza z grubsza „dla każdej wartości od 1 do n licząc 2 (3-1) wykonuj tę monadyczną akcję”.

Oczywistą zmianą byłoby obliczenie 1 i 3 lub 2 i 4 i wykorzystanie ich w pojedynczym zdarzeniu monadycznym, ale zasadniczo nie wykonujesz tam nieprawidłowej pracy.