2012-04-23 6 views
8

n行の文字列を文字列のリストに読み込もうとしています。私は下のコードのいくつかのバリエーションを試しましたが、何も機能しませんでした。n行を[String]に読み込みます

main = do 
    input <- getLine 
    inputs <- mapM getLine [1..read input] 
    print $ length input 

これは、次のエラーがスローされます。

Couldn't match expected type `a0 -> IO b0' 
       with actual type `IO String' 
    In the first argument of `mapM', namely `getLine' 
    In a stmt of a 'do' block: inputs <- mapM getLine [1 .. read input] 
    In the expression: 
     do { input <- getLine; 
      inputs <- mapM getLine [1 .. read input]; 
      print $ length input } 

そして

main = do 
    input <- getLine 
    let inputs = map getLine [1..read input] 
    print $ length input 

Couldn't match expected type `a0 -> b0' 
       with actual type `IO String' 
    In the first argument of `map', namely `getLine' 
    In the expression: map getLine [1 .. read input] 
    In an equation for `inputs': inputs = map getLine [1 .. read input] 

私はこれをどのように行うことができますがスローされますか?

+3

ところで、 'inputs < - mapM(const getLine)[1 .. read input]'は必要なものを正確に行います。問題は、 'getLine'を数字' [1 .. n] 'にマッピングしようとしていますが、' getLine'は関数ではありません。 'const'を使うことで、最初の引数を無視する関数に変換します。 – Vitus

+0

@Vitusそれは別の答えとして価値がある、私はそれを+1します。 – vikingsteve

答えて

42

使用replicateMControl.Monadから:

人に魚を与える/魚に男を教えるの精神で
main = do 
    input <- getLine 
    inputs <- replicateM (read input) getLine 
    print $ length inputs 

:あなたはHoogleを検索することで、この自分自身を発見した可能性があります。

あなたは持っている:そのアクションを実行するタイプのIO String

  • 回数を実行するために

    • アクション(タイプInt)あなたが欲しい

    • タイプIO [String]のアクション

    だから、search Hoogle for (IO String) -> Int -> (IO [String])でした。 replicateMが最初のヒットです。

  • 0

    このアクションを実行できるもう1つの方法は、純粋な複製とsequence :: (Traversable t, Monad m) => t (m a) -> m (t a) ツールを使用することです。最初に、カウントを求めて、その合計値を端末に出力するようにその整数を要求します。

    sumCountManyData :: IO() 
    sumCountManyData = putStr "How many integers to sum..? " 
            >> getLine 
            >>= sequence . flip replicate getLine . read 
            >>= print . sum . map read 
    
    関連する問題