Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Overloading with seq<'T>

In a project I'm experimenting with, I'm constantly multiplying sequence elements. I wanted to create an operator like this:

let (.*) (a:seq<'T>) (b:seq<'T>) = Seq.map2 (*) a b

However, in FSI it returns:

val ( .* ) : a:seq<int> -> b:seq<int> -> seq<int>

And the following fails:

  seq [1.0;2.0] .* seq [3.0;4.0];;
  -----^^^

stdin(16,6): error FS0001: This expression was expected to have type
    int    
but here has type
    float 

How can I make the operator work on a generic seq<'T> (provided 'T supports multiplication)?

like image 687
Talmage Avatar asked Aug 11 '26 15:08

Talmage


1 Answers

You need to add the inline keyword to your operator declaration so that the correct overload can be resolved at compile time:

let inline (.*) (a:seq<'T>) (b:seq<'T>) = Seq.map2 (*) a b
val inline ( .* ) : a:seq< ^T> -> b:seq< ^T> -> seq< ^a> when  ^T :  (static member ( * ) :  ^T *  ^T ->  ^a)
like image 109
TheInnerLight Avatar answered Aug 14 '26 08:08

TheInnerLight



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!