Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type inference of functions as arguments

Tags:

f#

I would like to write a function which takes several tupples as arguments and choose theirs ith elements and passes to another function, where i is given as another argument. I've tried sth like this:

let function (tup1:'A*'A) (tup2:'B*'B) i =
    otherFunction (i tup1) (i tup2)
function Tup1 Tup2 fst

I've got an error, because i was expected to be 'A*'A ->'A not 'B*'B->'B. Is it any way to make this code to work?

Thanks in advance.

like image 737
Artur Avatar asked Aug 22 '15 12:08

Artur


1 Answers

You basically want to pass an argument of type ∀'a.'a*'a->'a, but in F# (and other MLs), only rank-1 polymorphism is supported so you can't do this directly. The workaround is to define a new type with a generic method to emulate higher-rank polymorphism:

type Untupler =
    abstract Apply : 'a*'a -> 'a

let myFunction tup1 tup2 (i:Untupler) =
    otherFunction (i.Apply tup1) (i.Apply tup2)

myFunction Tup1 Tup2 { new Untupler with member __.Apply (x,y) = x }
like image 160
kvb Avatar answered Sep 28 '22 08:09

kvb