2015-05-11 2 views
-2

все Я хочу получить список чисел из GUI, чтобы внести некоторые изменения с помощью gtk2hs, и вернуть результат в GUI. Однако он получил много ошибок. Я новичок в Haskell, может кто-нибудь сказать мне, как это исправить. Благодаря!!gtk2hs: Не удалось совместить ожидаемый тип 'IO [Int]' с фактическим типом '[Int]'

import Graphics.UI.Gtk 
import Data.List 

main :: IO() 
main= do 
    initGUI 
    window <- windowNew 
    set window [windowTitle := "Text Entry", containerBorderWidth := 10] 

    vb <- vBoxNew False 0 
    containerAdd window vb 

    hb <- hBoxNew False 0 
    boxPackStart vb hb PackNatural 0 

    txtfield <- entryNew 
    boxPackStart hb txtfield PackNatural 5 
    button <- buttonNewFromStock stockInfo 
    boxPackStart hb button PackNatural 0 

    txtstack <- statusbarNew 
    boxPackStart vb txtstack PackNatural 0 
    id <- statusbarGetContextId txtstack "Line" 

    widgetShowAll window 
    widgetSetSensitivity button False 

    onEntryActivate txtfield (saveText txtfield button txtstack id) 
    onPressed button (statusbarPop txtstack id) 
    onDestroy window mainQuit 
    mainGUI 

    saveText :: Entry -> Button -> Statusbar -> ContextId -> IO() 
    saveText fld b stk id = do 
         txt <- entryGetText fld 
         result <- convert txt 
         lt <- first resultt 
         result2 <- combineTogether lt 
         mesg <- " is the first element of input text" ++ txt 

         widgetSetSensitivity b True 
         msgid <- statusbarPush stk id mesg 
         return() 
convert :: [Int] -> IO [Int] 
convert lstr = map read $ words lstr :: [Int] 

converttoStr lst = map show lst 

combineTogether :: [Int] -> IO[Char] 
combineTogether lst = intercalate " " (converttoStr lst) 

first :: [Int] -> IO [Int] 
first (x:xs) = xs 

Вот сообщение об ошибке:

[1 of 1] Compiling Main    (testproject.hs, testproject.o) 

testproject.hs:39:38: 
Couldn't match type ‘[]’ with ‘IO’ 
Expected type: IO Char 
    Actual type: [Char] 
In a stmt of a 'do' block: 
    mesg <- " is the first element of input text" ++ txt 
In the expression: 
    do { txt <- entryGetText fld; 
     result <- convert txt; 
     lt <- first result; 
     result2 <- combineTogether lt; 
     .... } 
In an equation for ‘saveText’: 
    saveText fld b stk id 
     = do { txt <- entryGetText fld; 
      result <- convert txt; 
      lt <- first result; 
      .... } 

testproject.hs:39:79: 
Couldn't match type ‘Int’ with ‘Char’ 
Expected type: [Char] 
    Actual type: [Int] 
In the second argument of ‘(++)’, namely ‘txt’ 
In a stmt of a 'do' block: 
    mesg <- " is the first element of input text" ++ txt 

testproject.hs:48:16: 
Couldn't match expected type ‘IO [Int]’ with actual type ‘[Int]’ 
In the expression: map read $ words lstr :: [Int] 
In an equation for ‘convert’: 
    convert lstr = map read $ words lstr :: [Int] 

testproject.hs:48:33: 
Couldn't match type ‘Int’ with ‘Char’ 
Expected type: String 
    Actual type: [Int] 
In the first argument of ‘words’, namely ‘lstr’ 
In the second argument of ‘($)’, namely ‘words lstr’ 

testproject.hs:51:23: 
Couldn't match expected type ‘IO [Char]’ with actual type ‘[Char]’ 
In the expression: intercalate " " (converttoStr lst) 
In an equation for ‘combineTogether’: 
    combineTogether lst = intercalate " " (converttoStr lst) 

testproject.hs:54:16: 
Couldn't match expected type ‘IO [Int]’ with actual type ‘[Int]’ 
In the expression: xs 
In an equation for ‘first’: first (x : xs) = xs 

ответ

4

Do-нотация синтаксический сахар для серии связывания операций. Имея это в виду, имеет смысл, что каждая строка в вашем блоке do-block должна иметь тип «IO», потому что именно так вы определили свою функцию.

Попробуйте изменить следующую строку

mesg <- " is the first element of input text" ++ txt 

в

let mesg = " is the first element of input text" ++ txt 

(что также эквивалентно)

mesg <- return " is the first element of input text" ++ txt 

Это должно решить проблему вы имеете на этой конкретной линии. И это делает даже больше смысла, если мы посмотрим на сигнатуры типа функции «возврата»:

Monad m => a -> m a 

Это говорит о том, «поставлять„A“, и я дам вам„а“завернуты внутри монады "(в этом случае монада IO)

Надеюсь, это немного поможет.

Смежные вопросы