patternMinor
Reading numbers from console until input isn't a number
Viewed 0 times
readingnumberisnuntilconsolenumbersinputfrom
Problem
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:
Is there a simpler (less code) solution?
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?
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:
or
if you want to defer the return of each input to after the last valid input has been entered.
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.toListif you want to defer the return of each input to after the last valid input has been entered.
Code Snippets
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)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.toListContext
StackExchange Code Review Q#155768, answer score: 4
Revisions (0)
No revisions yet.