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?
1 Answer 1
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.
-
\$\begingroup\$
Seq.takeWhile
makes it! I hoped there is an even shorter solution... but that one work fine, thanks :) \$\endgroup\$JanDotNet– JanDotNet2017年02月19日 19:29:14 +00:00Commented Feb 19, 2017 at 19:29