Reputation: 479
I am new to Haskell and I want to know how to print string and integer value returned by some function in Haskell as we simply do in C++.
#include <iostream>
using namespace std;
int solve(int a) {
return a * a;
}
int main() {
int cases, number;
cin >> cases;
for (int cs = 1; cs <= cases; cs++) {
cin >> number;
cout << "Case " << cs << ": " << solve(number) << endl;
}
return 0;
}
I tried similar in Haskell but no luck and getting error.
solve :: Int -> Integer
solve = …
main = do
n <- readLn
forM_ [1..n] (\i -> do
m <- readLn
printf "Case %d: %d" i (solve m))
Upvotes: 0
Views: 3471
Reputation: 116139
Use forM_ [1..n::Int]
to let the compiler know the type you want for n
. Otherwise there's not enough information for the readLn
to typecheck.
main :: IO ()
main = do
n <- readLn
forM_ [1..n::Int] (\i -> do
m <- readLn
printf "Case %d: %d\n" i (solve m))
printf
is not so used in Haskell when you do not need its fancy features (e.g. %04d
or more complex format strings). A more idiomatic way could be
main :: IO ()
main = do
n <- readLn
forM_ [1..n::Int] (\i -> do
m <- readLn
putStrLn $ "Case " ++ show i ++ ": " ++ show (solve m)
The function show
converts almost anything to a string.
Upvotes: 3