Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Creating a collection of integers from user input

Tags:

f#

I'm rather new to F# so the question may be fairly elementary. Still, I couldn't find any suggestion on SO.

I'm playing with an algorithmic task in F#. As a first step I want to create a collection of integers from user console input. The number of inputs is not defined. And I don't wont to use any while loops. I would prefer as much idiomatic approach as possible.

In a recursive function I'm reading the result and parsing it with Int32.TryParse. I match the bool result using match ... with. If successful then I attach a new value to a collection. Otherwise I return the collection.

Below is my code:

let rec getNumList listSoFar =
    let ok, num = Int32.TryParse(Console.ReadLine())
    match ok with
        | false -> listSoFar
        | true -> getNumList num::listSoFar

let l = getNumList []

And the error I get:

Type mismatch. Expecting a 'a
but given a 'a list

I'm aware I'm using types incorrectly, though I don't understand what exactly is wrong. Any explanation highly appreciated.

like image 220
PiotrWolkowski Avatar asked Nov 19 '25 03:11

PiotrWolkowski


1 Answers

In the match branch

| true -> getNumList num::listSoFar

You should use parenthesis:

| true -> getNumList (num::listSoFar)

Because function application has higher priority than the :: operator

like image 113
Petr Avatar answered Nov 21 '25 10:11

Petr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!