Constrained generic type to inherit the generic type in F #

let mapTuple f (a,b) = (fa, fb)

I am trying to create a function to apply function f to a tuple And return the result as a tuple. F# type inference says that mapTuple returns a’b *’b tuple. It also assumes that a and b are of the same type.

I want to be able to pass two Kind of different types as parameters. You would think that this doesn’t work because they all have to be passed as parameters to f. So I think it might work if they inherit from the same base class.

For what I want to achieve, this is a not very general function.

let mapTuple (f:Map<_,_> -> Map<'a,' b>) (a:Map,b:Map) = (fa, fb)

However, it will have a type mismatch error.

< p>What should I do? What do I want to achieve in F#?

There are clearly stated risks. A good enough solution may be to have a mapTuple, which accepts Two functions instead of one:

let mapTuple fa fb (a, b) = (fa a, fb b)

If you The original f of is generic, passing it as fa and fb will give you two concrete instances of the function with the type you are looking for. In the worst case, when a and b are of the same type, you only Need to pass the same function twice.

let mapTuple f (a,b) = (fa, fb)

I am trying Create a function, apply the function f to two items in the tuple, and return the result as a tuple. F# type inference says that mapTuple returns a’b *’b tuple. It also assumes that a and b are of the same type.

I want to be able to pass two different types as parameters. You would think that this does not work because they both have to be passed as parameters to f. So I think if they inherit from the same base class, it It may work.

For what I want to achieve, this is a not very general function.

let mapTuple (f:Map< _,_> -> Map<'a,'b>) (a:Map,b:Map) = (fa, fb)

However, it There will be a type mismatch error.

What should I do? What do I want to achieve in F#?

There are clearly stated risks. A good enough solution might be a mapTuple, which accepts two functions instead of one:

let mapTuple fa fb (a, b) = (fa a, fb b)

If your original f is generic, use it as fa and Passing fb will give you two concrete instances of the function with the type you are looking for. In the worst case, when a and b are of the same type, you only need to pass the same function twice.

Leave a Comment

Your email address will not be published.