6
\$\begingroup\$

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?

t3chb0t
44.6k9 gold badges84 silver badges190 bronze badges
asked Feb 19, 2017 at 13:14
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

answered Feb 19, 2017 at 16:13
\$\endgroup\$
1
  • \$\begingroup\$ Seq.takeWhile makes it! I hoped there is an even shorter solution... but that one work fine, thanks :) \$\endgroup\$ Commented Feb 19, 2017 at 19:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.