I’m new to haskell guys. I’m trying to write a gcd executable file.
ghc --make gcd
When I compile this code I’m getting the following error.
Couldn't match expected type `IO b0' with actual type `[a0]'
In a stmt of a 'do' block:
putStrLn "GCD is: " ++ gcd' num1 num2 ++ "TADA...."
In the expression:
do { putStrLn "Hello,World. This is coming from Haskell";
putStrLn "This is the GCD";
putStrLn "Frist Number";
input <- getLine;
.... }
In an equation for `main':
main
= do { putStrLn "Hello,World. This is coming from Haskell";
putStrLn "This is the GCD";
putStrLn "Frist Number";
.... }
I don’t understand where my problem is… Here is my code.
gcd' :: (Integral a) => a -> a -> a
gcd' x y = gcd' (abs x) (abs y)
where gcd' a 0 = a
gcd' a b = gcd' b (a `rem` b)
main = do
putStrLn "Hello,World. This is coming from Haskell"
putStrLn "This is the GCD"
putStrLn "Frist Number"
input <- getLine
let num1 = (read input)
putStrLn "Second Number"
input2 <- getLine
let num2 = read input2
putStrLn "GCD is: " ++ gcd' num1 num2 ++ "TADA...."
All I know is that read helps me convert my string into an int.
First, you need parentheses,
or infix function application
($):Without that, the line is parsed as
and the concatenation of the IO-action
putStrLn "GCD is: "with aStringis what causes the – somewhat cryptic, before one has enough experience – type error.From the context in that the line appears – in an
IO-do-block – it must have typeIO bfor someb. But the type inferred from the application of(++)is[a]for some typea. These types cannot be matched, and that’s what the compiler reports.Note that after fixing that, you also need to convert the result of
gcd'to aString,or you’ll see another type error.
From the comment
In general, yes. Instead of using
putStrLnwhich appends a newline to the output string, useputStrwhich doesn’t.In interactive mode (ghci), that works well.
stdoutis not buffered there. For compiled programmes,stdoutis usually line-buffered, that means it will not output anything until a newline shall be output or the buffer is full.So for a compiled programme, you need to explicitly flush the output buffer,
or turn off buffering altogether
But at least the latter method used to not work on Windows (I’m not sure whether that’s fixed, nor am I absolutely sure that
hFlushing works on Windows).