kuskmen
kuskmen

Reputation: 3775

F# is unable to infer type arguments after annotation

So I have some json response content represented as string and I want to get its property names.

What I am doing

 let properties = Newtonsoft.Json.Linq.JObject.Parse(responseContent).Properties()
 let propertyNames, (jprop: JProperty) = properties.Select(jprop => jprop.Name);

According to this answer I needed to annotate the call to the extension method, however, I still get the error.

A unique overload for method 'Select' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,'TResult>) : Collections.Generic.IEnumerable<'TResult>, (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,int,'TResult>) : Collections.Generic.IEnumerable<'TResult>

Am I doing something wrong?

Upvotes: 0

Views: 164

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

First, the syntax x => y you're trying to use is C# syntax for lambda expressions, not F# syntax. In F#, the correct syntax for lambda-expressions is fun x -> y.

Second, the syntax let a, b = c means "destructure the pair". For example:

let pair = (42, "foo")
let a, b = pair  // Here, a = 42 and b = "foo"

You can provide a type annotation for one of the pair elements:

let a, (b: string) = pair

But this won't have any effect on pair the way you apparently expect it to work.

In order to provide type annotation for the argument of a lambda expression, just annotate the argument, what could be simpler?

fun (x: string) -> y

So, putting all of the above together, this is how your line should look:

let propertyNames = properties.Select(fun (jprop: JProperty) -> jprop.Name)

(also, note the absence of semicolon at the end. F# doesn't require semicolons)


If you have this level of difficulty with basic syntax, I suggest you read up on F# and work your way through a few examples before trying to implement something complex.

Upvotes: 3

Related Questions