2017-12-22 12 views
1

コンソールから文字列を読み込み、それをカスタムデータ型に解析する単純な関数を書いてみたいと思います。単純な入力関数Haskell

私の試み:

data Custom = A | B Int | C String deriving Read 

getFormula::IO Custom 
getFormula = do 
    putStrLn("Introduce una formula: ") 
    toParse <- getLine 
    return read toParse::Custom 

しかし、これは動作しませんし、私は結果のコンパイルエラーを解釈する方法がわかりません。これをどうやって解決するのですか? IO機能の仕組みについて私が誤解していることは何ですか?


EDIT:これはGCHI

に私は、ファイルをロードしようとすると、私が取得エラーです
test.hs:7:5: 
Couldn't match type ‘String -> a0’ with ‘Custom’ 
Expected type: String -> Custom 
    Actual type: String -> String -> a0 
The function ‘return’ is applied to two arguments, 
but its type ‘(String -> a0) -> String -> String -> a0’ 
has only three 
In a stmt of a 'do' block: return read toParse :: Custom 
In the expression: 
    do { putStrLn ("Introduce una formula: "); 
     toParse <- getLine; 
     return read toParse :: Custom } 

test.hs:7:5: 
Couldn't match expected type ‘IO Custom’ with actual type ‘Custom’ 
In a stmt of a 'do' block: return read toParse :: Custom 
In the expression: 
    do { putStrLn ("Introduce una formula: "); 
     toParse <- getLine; 
     return read toParse :: Custom } 
In an equation for ‘getFormula’: 
    getFormula 
     = do { putStrLn ("Introduce una formula: "); 
      toParse <- getLine; 
       return read toParse :: Custom } 
+1

'getLine'と' read'の代わりに 'readLn'を直接使うことができます。 – 4castle

答えて

2

次の2個のタイプのエラーを持っている:

括弧を使用アプリケーションの順序を指定します。もう一つは理解することは簡単です:

getFormula::IO Custom 

getFormulaタイプIO Customを持つように宣言されています。

return read toParse::Custom 

...しかし、最後の表現は、タイプがCustomであると主張しています。 IO CustomCustomと同じではないため、コンパイラは不平を言います。


ところで、あなたのスペーシングはちょっと奇妙です。なぜあなたは::が左右の識別子に対して渋滞していますか?

return read toParse :: Custom 

人通りの少ないともあまり誤解を招くになります。:: Custom部分は、左の式全体だけでなく、単一の変数に適用されます。


最初のエラーは少し混乱しているが、それは重要なヒントが含まれています:The function ‘return’ is applied to two arguments

returnは一つだけの引数を取ります。

  • return read toParse 
    

    も型注釈を固定するために

    return (read toParse) 
    

    する必要があり、次のいずれかを使用することができます少しぎこちなく:

    少しすっきり
    return (read toParse) :: IO Custom 
    
  • IOを指定する必要はありません):

    return (read toParse :: Custom) 
    
  • 最も簡単な解決策:

    return (read toParse) 
    

    あなたは明示的にすべてここにタイプを指定する必要はありません。コンパイラは、getFormula :: IO Custom宣言のためにCustomを探していることを既に知っています。

2

return関数は、1つの引数を持っていますが、あなたはそれを2を与えている - 最初のものですreadであり、第2のものはtoParseである。

return (read toParse :: Custom) 
関連する問題