簡體   English   中英

無法將預期的類型“ IO b0”與實際類型“ [a0]”匹配

[英]Couldn't match expected type `IO b0' with actual type `[a0]'

我是Haskell家伙的新手。 我正在嘗試編寫gcd可執行文件。

ghc --make gcd

當我編譯此代碼時,出現以下錯誤。

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";
             .... }

我不明白我的問題在哪里...這是我的代碼。

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

我所知道的是, read幫助我將字符串轉換為int。

首先,需要括號

putStrLn ("GCD is: " ++ gcd' num1 num2 ++ "TADA....")

或中綴函數應用程序($)

putStrLn $ "GCD is: " ++ gcd' num1 num2 ++ "TADA...."

否則,該行將解析為

(putStrLn "GCD is: ") ++ gcd' num1 num2 ++ "TADA...."

以及IO操作putStrLn "GCD is: "String是導致-類型錯誤(在人們沒有足夠的經驗之前)的原因。

從上下文開始,該行出現-在IO -do-block中,它的某些b必須具有IO b類型。 但是從(++)應用程序推斷出的類型對於某些類型a[a] 這些類型無法匹配,這就是編譯器報告的內容。

請注意,修復該問題之后,還需要將gcd'的結果轉換為String

putStrLn $ "GCD is: " ++ show (gcd' num1 num2) ++ "TADA...."

否則您會看到另一個類型錯誤。


從評論

為了使我的程序看起來更好。 有沒有辦法使輸入區域位於語句旁邊而不是向下一行?

一般來說,是的。 與其使用putStrLn不將其在輸出字符串后附加一個換行符) putStr ,不使用它。

putStr "Second Number: "
input2 <- getLine

在交互模式(ghci)中,效果很好。 stdout沒有在那里緩沖。 對於已編譯的程序, stdout通常是行緩沖的,這意味着在輸出換行符或緩沖區已滿之前, stdout不會輸出任何內容。

因此,對於已編譯的程序,您需要顯式刷新輸出緩沖區,

import System.IO -- for hFlush

putStr "Second Number: "
hFlush stdout
input2 <- getLine

或完全關閉緩沖

import System.IO

main = do
    hSetBuffering stdout NoBuffering
    ...

但是至少后一種方法以前在Windows上不起作用(我不確定這是否是固定的,也不能絕對確定hFlush ing在Windows上可以工作)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM