Types and Functions

Consider the following:

type T () = member xy = 4 let a = let fn () (k: T) = () fn () let b = let fn () (k: System.IO.Directory) = () fn () 

a does not work while b is ok. Error message:

The value of 'a' was inferred in order to have a common type val a: ('_a β†’ unit), when' _a:> T either make the arguments in 'a' explicit, or, if you are not going to use it, be general, add type annotation

Why and how to fix it?

+4
source share
3 answers

The error message itself tells you what you need to do - add an annotation like:

 let a : T -> unit = let fn () (k: T) = () fn () 

The reason you see the error in the first place is because the compiler is trying to generalize the definition of a (see this part of the specification), which leads to the odd signature that you see in the error message.

The reason you don't need to do this for b is because System.IO.Directory sealed, so there is no need to generalize.

+6
source

You are faced with a value constraint because a looks like a constant but returns a function. Take a look at this question:

General F # Limit Error Errors

One easy way to solve this problem is to add a variable to the definition of a .

 let ax = let fn () (k: T) = () fn () x 

I don’t know why it works with some types, what happens in case b

+1
source

If T, where is the entry instead of the class, this will work. But for some reason you have to specify it for the compiler, if T is a class,

 type T () = member xy = 4 let a<'U when 'U :> T> = let fn () (k: 'U) = () fn () let test0 = a<T> (T()) // You can be explicit about T, let test1 = a (T()) // but you don't have to be. 

edit: So, I played around a bit with this, and, oddly enough, the compiler seems to be satisfied only with any type of constraint:

 type T () = member xy = 4 type S () = member xz = 4.5 let a<'U when 'U :> S> = let fn () (k: T) = () fn () let test = a (T()) // Is OK let test = a<T> (T()) // Error: The type 'T' is not compatible with the type 'S' 

Type S has nothing to do with the code above, but the compiler with pleasure just has a restriction of any type.

0
source

Source: https://habr.com/ru/post/1394608/


All Articles