Problem statement
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the monsoon, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter. Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after \$N\$ growth cycles?
Input Format
The first line contains an integer, \$T\$, the number of test cases. \$T\$ lines follow. Each line contains an integer, \$N\$, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10 0 <= N <= 60
Sample Input: #01:
2 3 4
Sample Output: #01:
6 7
Explanation: #01:
There are 2 testcases.
N = 3:
* the height of the tree at the end of the 1st cycle = 2 * the height of the tree at the end of the 2nd cycle = 3 * the height of the tree at the end of the 3rd cycle = 6N = 4:
- the height of the tree at the end of the 4th cycle = 7
This is my accepted solution:
module Main where
import Control.Monad(mapM_)
main = do
let base_height = 1
n_test_cases <- readLn
test_cases <- getList n_test_cases
mapM_ (\i -> putStrLn $ show $ utopianTreeHeight base_height
(test_cases !! i)) [0..n_test_cases - 1]
getList :: Int -> IO [Int]
getList n =
if n == 0
then return []
else
do
x <- readLn
xs <- getList (n - 1)
return (x:xs)
utopianTreeHeight :: Int -> Int -> Int
utopianTreeHeight present_height 0 = present_height
utopianTreeHeight present_height cycles =
if odd cycles
then 2 * (utopianTreeHeight present_height (cycles - 1))
else
1 + (utopianTreeHeight present_height (cycles - 1))
So, does this solution show good Haskell style? What could be improved? I have doubts especially regarding the way I deal with the IO (which was not provided by Hackerrank), as it was the first time I read about and applied the Haskell way of doing it.