Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one call bool.TryParse in F#

I need to call bool.TryParse in F# and I'm having a little difficulty with the compiler / Ionide.

Ex.

let value = true
let parsable = bool.TryParse("True", &value)

There error I'm seeing in Ionide for VSCode looks like the following.

val value : bool Full name: value

Assembly: example3

The type 'ByRefKinds.InOut' does not match the type 'ByRefKinds.In'F# Compiler(1)

This is the first example that I've used call by ref keywords and syntax in F# so I'm not sure what I'm doing wrong and the byrefs documentation doesn't seem to be of much help on understanding this particular scenario.

like image 589
jpierson Avatar asked Aug 11 '26 20:08

jpierson


1 Answers

It turns out that the main thing I was missing in my example was that value wasn't mutable as it would need to be when called in this context.

Working example:

let mutable value = true
let parsable = bool.TryParse("True", &value)

This solution came to me after reading a slightly related GitHub issue related to Span<T> and then also playing around in dotnet fsi which at least gave me the following clue.

  let parsable = bool.TryParse("True", &value);;
  -------------------------------------^^^^^^

stdin(34,38): error FS3230: A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...'

As it turns out however F# also seems to have sntaxtic sugar around the Try-Parse pattern which I began to recall after playing around with this example further. This reduced into the below alternative solution to calling bool.TryParse.

let value = true
let (parsable, _) = bool.TryParse "True"

Alternatively without having to bind parsable and to specify the default value within a single expression the following example may be more elegant.

let value = match bool.TryParse "True" with
| true, value -> value
| false, _ -> true

Perhaps there are pros and cons to the different ways of calling bool.TryParse and other Try-Parse methods but the important thing is that I found some solutions that work and get me past the initial stumbling blocks with regard to lack of F# documentation on the subject.

like image 149
jpierson Avatar answered Aug 14 '26 07:08

jpierson



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!