2016-04-26 5 views
0

Beim Lernen Haskell "für ein besseres gut" (aka, um die Prüfungen für funktionale Sprachen zu bestehen), Ich lief in einen seltsamen Fehler. Ich erhalte in jedem Do-Block (außer dem ersten) einen Typ-Mismatch-Fehler. Um genauer zu sein, scheint der Compiler eine Liste von etwas zu erwarten.Haskell-Typ stimmt nicht überein Do-Block

Ich denke, es hat etwas mit den IO-Operationen zu tun ...

Code:

-- chaos.hs 
import System.IO 

main :: IO() 
main = do           -- no error 
     inl <- openFile "dictionary.txt" ReadMode 
     let lang = extractLang (inl) 
     hClose inl 

extractLang :: Handle -> String 
extractLang file = do        --error 
        eof <- hIsEOF file 
        if eof 
         then do hClose file   --error 
           "none" 
         else do line <- hGetLine file --error 
           if length (words line) == 1 
           then line 
           else extractLang file 

das Fehlerprotokoll:

chaos.hs:12:27: 
Couldn't match type ‘IO’ with ‘[]’ 
Expected type: [Bool] 
    Actual type: IO Bool 
In a stmt of a 'do' block: eof <- hIsEOF file 
In the expression: 
    do { eof <- hIsEOF file; 
     if eof then 
      do { hClose file; 
       .... } 
     else 
      do { line <- hGetLine file; 
       .... } } 

chaos.hs:14:31: 
    Couldn't match type ‘IO’ with ‘[]’ 
    Expected type: [()] 
     Actual type: IO() 
    In a stmt of a 'do' block: hClose file 
    In the expression: 
     do { hClose file; 
      "none" } 

chaos.hs:16:39: 
    Couldn't match type ‘IO’ with ‘[]’ 
    Expected type: [String] 
     Actual type: IO String 
     In a stmt of a 'do' block: line <- hGetLine file 
     In the expression: 
     do { line <- hGetLine file; 
      if length (words line) == 1 then line else extractLang file 
} 

Antwort

4

Sie sind völlig Recht, dass es hat mit den IO-Operationen zu tun. Zuerst ist der richtige Typ für extractLangHandle -> IO String. Zweitens fehlen ein paar return s (aus dem gleichen Grund):

extractLang :: Handle -> IO String 
extractLang file = do         
        eof <- hIsEOF file 
        if eof 
         then do hClose file    
           return "none"   -- return 
         else do line <- hGetLine file 
           if length (words line) == 1 
           then return line  -- return 
           else extractLang file 
Verwandte Themen