Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we satisfy F# static member constraints with type extensions?

I'd like to be able to extend types from other libraries with static methods to enable generic arithmetic. Take, for example, the newly minted SIMD-friendly fixed-size VectorN types from Microsoft. They define Zero, they define (+), they define (/), but I can't use Array.average on them because they don't define DivideByInt, which I'd be happy to:

open System.Numerics
type Vector2f with 
  static member DivideByInt (v:Vector2f) (i:int) = v / Vector2f(single i, single i)
let bigArray : Vector2f[] = readABigFile()
printf "the average is %A" (Array.average bigArray)

But it won't let me compile, complaining

error FS0001: The type 'Vector2f' does not support the operator 'DivideByInt'

Why does this limitation exist in the F# compiler?

(Edit: essentially the same question was asked previously.)

like image 549
Sebastian Good Avatar asked Aug 17 '14 04:08

Sebastian Good


People also ask

Why humans are never satisfied with what they have?

Nature and evolution Humans are not designed to be happy, or even content. Instead, we are designed primarily to survive and reproduce, like every other creature in the natural world. A state of contentment is discouraged by nature because it would lower our guard against possible threats to our survival.

What is a person who is never satisfied?

If someone can't be satisfied, she is insatiable.

What makes a person satisfied?

It is our general feeling about our life and how pleased we are with how it's going. There are many factors that contribute to life satisfaction from a number of domains, including work, romantic relationships, relationships with family and friends, personal development, health and wellness, and others.


1 Answers

It is not currently possible to define an operator overload in a type extension. There is an F# language user voice item for this (with quite a lot of votes) and so this is something that might change in future versions of F# (I think it would be great addition that fits nicely with the F# design).

If you absolutely need something like this today, you can either create a lightweight wrapper for your type that adds the operators, or you can use a (somewhat scary) trick that lets you hide the standard operator with a new overloaded one. The following question has both examples: Global operator overloading in F#

like image 156
Tomas Petricek Avatar answered Oct 09 '22 03:10

Tomas Petricek