# Reading numbers from console until input isn't a number

I want to read N numbers (Nmax = 100) from console into a list. N is not known, but the first input that is not a number may break the reading process... However the solution should be as simple as possible, so I just read 100 lines:

let numbers = [1..100]
|> List.map (fun x -> Int32.TryParse(Console.ReadLine()))
|> List.filter (fun (isNum, num) -> isNum)
|> List.map (fun (isNum, num) -> num)


Is there a simpler (less code) solution?

Your code does not read numbers from the "console until input isn't a number", but reads 100 inputs strings from the console and returns those that can be converted to integers.

If you want to read numbers from the console "until input isn't a number", you could do something like this:

let numbers1 max = seq {for x in 1..max do yield Int32.TryParse(Console.ReadLine()) }
|> Seq.takeWhile (fun (b, x) -> b)
|> Seq.map (fun (b, x) -> x)


or

let numbers2 max = seq {for x in 1..max do yield Int32.TryParse(Console.ReadLine()) }
|> Seq.takeWhile (fun (b, x) -> b)
|> Seq.map (fun (b, x) -> x)
|> Seq.toList


if you want to defer the return of each input to after the last valid input has been entered.

• Seq.takeWhile makes it! I hoped there is an even shorter solution... but that one work fine, thanks :) – JanDotNet Feb 19 '17 at 19:29