How to call System.IO.TextWreader.ReadLine to read stdin until EOF?

Answered How to call System.IO.TextWreader.ReadLine to read stdin until EOF?

  • Tuesday, January 01, 2013 11:58 PM
     
      Has Code

    I'm new to F# and I'm trying to translate this C# code:

      static System.IO.TextWriter outp = System.Console.Out;
      static System.IO.TextReader inp = System.Console.In;
       string line;
          while ( (line = inp.ReadLine()) != null )
            outp.WriteLine("echo data from stdin: "+ line);
    

    I'm not sure how to do the while loop in F# so it reads the line variable and also terminates on EOF.

    Can someone translate this for me?

    Thanks

    Siegfried


    siegfried heintze

All Replies

  • Wednesday, January 02, 2013 3:23 AM
     
     Answered Has Code
    > let lines =
    -     Seq.initInfinite (fun _ -> System.Console.In.ReadLine())
    -     |> Seq.takeWhile(fun line -> line <> null);;
    
    val lines : seq<string>
    
    > for line in lines do printfn "%s" line;;
    test
    test
    opr
    opr
    mmt
    mmt
    ^D
    ♦
    ^Z
    val it : unit = ()
    >

    • Proposed As Answer by nielsb Wednesday, January 02, 2013 10:40 AM
    • Marked As Answer by siegfried_ Thursday, January 03, 2013 1:19 AM
    •  
  • Thursday, January 03, 2013 1:31 AM
     
      Has Code

    This works. However, the statement

    for line in lines do printfn "%s" line

    only works once! Why cannot I print out the contents of lines twice using the exact same statement? Why is not not necessary to declare line as mutable?

    Thanks

    Siegfried


    siegfried heintze

  • Thursday, January 03, 2013 1:52 AM
     
     

    My example is a lazy sequence. It is recalculated each time you try to enumerate over it.

    To use input multiple times you must cache it via Seq.cache.