F# operator overloading riddle 2 - f#

In F# operator overloading seems powerful but also tricky to get right.
I have following class:
type Value<'T> =
with
static member inline (+) (a : Value<'U>, b: Value<'U>) : Value<'U> =
do stuff
If i define another overload for + with :
static member inline (+) (a : Value<'U>, b: 'U) : Value<'U> =
do stuff
It works. But if i want a symmetric operator:
static member inline (+) (b: 'U, a : Value<'U>) : Value<'U> =
do stuff
The compiler complains:
let a = Value<int>(2);
let b = a + 3 // ok
let c = 3 + a //<-- error here
Error 3 Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations
Is there a way around this and stay generic?
I am using F# 3.1
Thanks

Removing the type annotations will solve the issue you pointed out, but you didn't notice there is another issue: try invoking the first overload, the compiler will not know which overload to call. It's a shame the overload resolution doesn't pick up the right one.
One tricky way to get everything working at compile time is to declare only the first overload into the type, and for the rest use the trick of redefining the (+) operator using an intermediate type:
type Value<'T> = Value of 'T with
static member inline (+) (Value a, Value b) = Value (a + b)
type Sum = Sum with
static member inline (?<-) (Sum, a, b) = a + b
static member inline (?<-) (Sum, Value a, b) = Value (a + b)
static member inline (?<-) (Sum, b, Value a) = Value (a + b)
let inline (+) a b :'t = (?<-) Sum a b
// test
let v = Value(2)
let a = v + v
let b = v + 3
let c = 3 + v
let d = Value(Value 7) + Value(Value 10)
let e = 5 + 7
UPDATE
I've found another workaround which I prefer since it does not require redefining the (+) operator, the trick is to create a base class and move some overloads there:
type BaseValue<'T>(v : 'T) =
member x.V = v
type Value<'T>(v : 'T) =
inherit BaseValue<'T>(v : 'T)
static member inline (+) (a : Value<_>, b: Value<_>) = Value(b.V+a.V)
type BaseValue with
static member inline (+) (a: BaseValue<_>, b) = Value(b+a.V)
static member inline (+) (b, a: BaseValue<_>) = Value(b+a.V)
// test
let v = Value(2)
let a = v + v
let b = v + 3
let c = 3 + v
let d = Value(Value 7) + Value(Value 10)
let e = 5 + 7

I think the problem lies in the fact that there is no way to resolve between the first and, say, the second overload when the second parameter to the second overload is a Value<'T> itself.
Here is a complete version that causes the error:
type Value<'T>(v : 'T) =
member x.V = v
with
static member inline (+) (a : Value<'U>, b: Value<'U>) : Value<'U> =
Value<'U>(b.V+a.V)
static member inline (+) (a : Value<'U>, b: 'U) : Value<'U> =
Value<'U>(b+a.V)
static member inline (+) (b: 'U, a : Value<'U>) : Value<'U> =
Value<'U>(b+a.V)
let a = Value<int>(2);
let b = a + 3
let c = 3 + a
I'd say write one operator overload, and do pattern matching on type inside it? Ugly, I know.

Related

How can I define overloaded operators with operands whose type definitions I do not control in F#?

I have 3 types, A, B, and C in F#. Two of the types, A and B I do not have the ability to modify code for. Type C is a type that I control.
I with to write overloaded operators such as -
type C () =
static member (><) (alpha : A) (beta : B) : C = zeta alpha beta
static member (><) (beta : B) (alpha : A) : C = omega alpha beta
When I attempt to invoke the operator, the compile issues the following error -
Error FS0043 None of the types 'A, B' support the operator '><'
How can I workaround the issue such that I can define overloaded operators with operands whose type definitions I do not control? The only type whose definition I do control is the result type, C!
Since C doesn't appear in the input parameters it won't work, at least as long as type extensions are not taken into account in overload resolution with trait calls.
So you'll have to include C and define the operator at global level:
type A = A
type B = B
type C () = class end
let zeta _ _ = C ()
let omega _ _ = C ()
type C with
static member (><) (_:C, alpha : A) = fun (beta : B) -> zeta alpha beta : C
static member (><) (_:C, beta : B) = fun (alpha : A) -> omega alpha beta: C
let inline (><) x y = (Unchecked.defaultof<C> >< x) y
// Test
let x = A >< B
// val x : C
Note: you can use a different operator name internally if you want

How to constrain type parameter must be an algebraic type (int, float, BigInteger, BigRational, ...)

-- While there are some questions on the net wrt. type constraints already, I didn't find one that can help me solving my issue. --
Goal: I want to create my own Vector/Matrix types, but so, that the implementation does not lock in to a speicific BigRational (or alike) type. All I'd prefer to require is the standard algebraic operations on such types (+ - * / % equality).
open System
type Foo<'T> (value: 'T) =
member inline __.Value : 'T = value
static member inline Add (a: Foo<'T>) (b: Foo<'T>) =
Foo<'T>(a.Value + b.Value)
module Foo =
let inline Create (v) = Foo(v)
let log (foo: #Foo<_>) =
printfn "Foo: %s" (foo.Value.ToString())
[<EntryPoint>]
let main argv =
Foo.log (Foo.Create("hi ho"))
Foo.log (Foo<int>(31415))
Foo.log (Foo<float>(3.1415))
Foo.log (Foo<int>.Add (Foo.Create(3)) (Foo.Create(4)))
let a = Foo.Create(13)
let b = Foo.Create(3.1415)
Foo.log (Foo<int>.Add (a.Value) (a.Value))
Foo.log (Foo<float>.Add (b.Value) (b.Value))
0 // return an integer exit code
I cannot get this tiny example code to compile for more than one single type, such as Foo<int> as well as Foo<float>. How could I do it right?
Many thanks in advance,
Christian.
You almost have it, actually.
In order to create a function that accepts any type that has a + operator, this function must have statically-resolved type parameters (SRTP). For this, it must be inline, which your Add is so that's ok. However here Add is not a generic method: it's a method on the generic type Foo<'T>, so it receives its 'T parameter from it. And a type cannot have SRTP.
A simple fix is to move Add from being a method on the type Foo<'T> to being a function in the module Foo. Then it will become actually generic.
open System
type Foo<'T> (value: 'T) =
member inline __.Value : 'T = value
module Foo =
let inline Create (v) = Foo(v)
let inline Add (a: Foo< ^T>) (b: Foo< ^T>) =
Foo< ^T>(a.Value + b.Value)
let log (foo: #Foo<_>) =
printfn "Foo: %s" (foo.Value.ToString())
[<EntryPoint>]
let main argv =
Foo.log (Foo.Create("hi ho"))
Foo.log (Foo<int>(31415))
Foo.log (Foo<float>(3.1415))
Foo.log (Foo.Add (Foo.Create(3)) (Foo.Create(4)))
let a = Foo.Create(13)
let b = Foo.Create(3.1415)
Foo.log (Foo.Add a a)
Foo.log (Foo.Add b b)
0
I think all you need is the inline keyword if you just want to propagate the member constraints of F#'s overloaded arithmetic operators.
type Foo<'T> (value : 'T) =
member __.Value = value
static member inline (+) (a : Foo<_>, b : Foo<_>) = Foo(a.Value + b.Value)
// static member
// ( + ) : a:Foo< ^a> * b:Foo< ^b> -> Foo< ^c>
// when ( ^a or ^b) : (static member ( + ) : ^a * ^b -> ^c)
Now you can add two Foos of the same type that support a static member (+), Foo 3 + Foo 4 or Foo 3.14 + Foo 3.14, even Foo(Foo 3) + Foo(Foo 4); but not Foo 3 + Foo 3.14. You may still instantiate types that do not possess such member.

Extension method with F# function type

The MSDN doc on Type Extensions states that "Before F# 3.1, the F# compiler didn't support the use of C#-style extension methods with a generic type variable, array type, tuple type, or an F# function type as the “this” parameter." (http://msdn.microsoft.com/en-us/library/dd233211.aspx)
How can be a Type Extension used on F# function type? In what situations would such a feature be useful?
Here is how you can do it:
[<Extension>]
type FunctionExtension() =
[<Extension>]
static member inline Twice(f: 'a -> 'a, x: 'a) = f (f x)
// Example use
let increment x = x + 1
let y = increment.Twice 5 // val y : int = 7
Now for "In what situations would such a feature be useful?", I honestly don't know and I think it's probably a bad idea to ever do this. Calling methods on a function feels way too JavaScript-ey, not idiomatic at all in F#.
You may simulate the . notation for extension methods with F#'s |> operator. It's a little clumsier, given the need for brackets:
let extension f x =
let a = f x
a * 2
let f x = x*x
> f 2;;
val it : int = 4
> (f |> extension) 2;;
val it : int = 8
> let c = extension f 2;; // Same as above
val c : int = 8

F# operator overloading riddle

In F# operator overloading seems powerful but also tricky to get right.
I have following class:
type Value<'T> =
with
static member inline (+) (a : Value<'U>, b: Value<'U>) : Value<'U> =
do stuff
If i define another overload for + with :
static member inline (+) (a : Value<'U>, b: 'U) : Value<'U> =
do stuff
It works. But if i want a symmetric operator:
static member inline (+) (b: 'U, a : Value<'U>) : Value<'U> =
do stuff
The compiler complains:
let a = Value<int>(2);
let b = a + 3 // ok
let c = 3 + a //<-- error here
Error 3 Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations
Is there a way around this and stay generic?
I am using F# 3.1
Thanks
The compiler never has a choice: When you apply the (+) operator, you either give it something of type int or something of type Value<'U>. Something of type int cannot be considered of type Value<'U>, and vice versa.
Let's try this in the interpreter. I made the two implementations output A and B so we can tell which is being called:
> type Value<'T> =
- { a : 'T }
- with
- static member inline (+) (a : Value<'U>, b: Value<'U>) : Value<'U> =
- printfn "A"; a
- static member inline (+) (a : Value<'U>, b: int) : Value<'U> =
- printfn "B"; a
- ;;
type Value<'T> =
{a: 'T;}
with
static member ( + ) : a:Value<'U> * b:Value<'U> -> Value<'U>
static member ( + ) : a:Value<'U> * b:int -> Value<'U>
end
Now we have a type. Let's make a value of it.
> let t = { a = "foo" };;
val t : Value<string> = {a = "foo";}
We can now try the overloads. First int:
> t + 4;;
B
val it : Value<string> = {a = "foo";}
Ok. Now Value<string>:
> t + t;;
A
val it : Value<string> = {a = "foo";}
As stated in another answer, my preferred solution would be to use a base class for some overloads:
type BaseValue<'T>(v : 'T) =
member x.V = v
type Value<'T>(v : 'T) =
inherit BaseValue<'T>(v : 'T)
static member inline (+) (a : Value<_>, b: Value<_>) = Value(b.V+a.V)
type BaseValue with
static member inline (+) (a: BaseValue<_>, b) = Value(b+a.V)
static member inline (+) (b, a: BaseValue<_>) = Value(b+a.V)
// test
let v = Value(2)
let a = v + v
let b = v + 3
let c = 3 + v
let d = Value(Value 7) + Value(Value 10)
let e = 5 + 7
Note that this problem disappears if you use the same type argument on your members as you do on the class itself:
type Value<'t when 't : (static member (+) : 't * 't -> 't)> = V of 't with
static member inline (+)(V(x:'t), V(y:'t)) : Value<'t> = V(x+y)
static member inline (+)(V(x:'t), y:'t) : Value<'t> = V(x+y)
static member inline (+)(x:'t, V(y:'t)) : Value<'t> = V(x+y)
This means that you can't create instances of type Value<obj> any more, but might meet your needs.
This operator definition is not sensible, though interestingly, neither is the compiler's reaction.
First of all, think about the intended return type of adding two Value<_> objects. It could be Value<Value<_>>! Language semantics aside, there is no reason to assume that a fully generic type like this shouldn't be nested within itself. This + operator is ill-defined. Type inference will always fail on the overload that adds two Value<_> instances, as the compiler will be unable to resolve the ambiguity.
But the more fundamental question is: what does this operator even mean? Add values and maybe wrap them in an extra type? Those are two entirely different operations; I don't see the merit of combining them, let alone implicitly and in a possibly ambiguous manner. It might save a lot of hassle to only define addition for two Value instances and construct them explicitly where needed.
That aside, it looks like the compiler is quite unintuitive in this case. Someone who knows the F# specification in detail may be able to tell whether it's a bug or inconsistent design, but look at how similar variants behave:
type Value<'T> =
{ Raw : 'T }
static member inline (+) (v, w) = { Raw = v.Raw + w.Raw }
static member inline (+) (v, a) = { Raw = v.Raw + a }
static member inline (+) (a, v) = { Raw = a + v.Raw }
let a = { Raw = 2 }
let b = a + 3 // ok
let c = 3 + a // ok
let d = { Raw = obj() } // No problemo
Too far off? Try this:
type Value<'T> =
val Raw : 'T
new (raw) = { Raw = raw }
static member inline (+) (v : Value<_>, w : Value<_>) = Value(v.Raw + w.Raw)
static member inline (+) (v : Value<_>, a) = Value(v.Raw + a)
static member inline (+) (a, v : Value<_>) = Value(a + v.Raw)
let a = Value(2)
let b = a + 3 // OK
let c = 3 + a // OK
let d = Value(obj) // No problemo
Not sure what is going on here, but it's not very consistent.

C# library overloads ^ operator. How to use ** instead?

The Symbolism library overloads arithmetic operators. Although it's written in C# I can use it from F#:
open Symbolism
let x = new Symbol("x")
let y = new Symbol("y")
let z = new Symbol("z")
printfn "%A" (2*x + 3 + 4*x + 5*y + z + 8*y)
the output:
3 + 6 * x + 13 * y + z
However, it also overloads ^ for powers. This of course doesn't play well with F#.
As a step towards a workaround, I exported a method group for powers:
printfn "%A" (Aux.Pow(x, 2) * x)
output:
x ^ 3
How can I overload ** to use the Aux.Pow method group instead?
I can do something like this:
let ( ** ) (a: MathObject) (b: MathObject) = Aux.Pow(a, b)
And that does work for MathObject values:
> x ** y * x;;
val it : MathObject = x ^ (1 + y)
But Aux.Pow is overloaded for int as well:
public static MathObject Pow(MathObject a, MathObject b)
{ return new Power(a, b).Simplify(); }
public static MathObject Pow(MathObject a, int b)
{ return a ^ new Integer(b); }
public static MathObject Pow(int a, MathObject b)
{ return new Integer(a) ^ b; }
Any suggestions welcome!
You can use the trick described here like this:
open Symbolism
type MathObjectOverloads =
| MathObjectOverloads
static member (?<-) (MathObjectOverloads, a: #MathObject, b: int) = MathObject.op_ExclusiveOr(a, b)
static member (?<-) (MathObjectOverloads, a: #MathObject, b: #MathObject) = MathObject.op_ExclusiveOr(a, b)
static member (?<-) (MathObjectOverloads, a: System.Int32, b: #MathObject) = MathObject.op_ExclusiveOr(a, b)
let inline ( ** ) a b = (?<-) MathObjectOverloads a b
let two = Integer(2)
let three = Integer(3)
two ** three
two ** 3
2 ** three
Unlike in the linked answer, we have to use the (?<-) operator because it's the only operator that can take 3 arguments instead of 2, and we need to overload on both the left and right side of the ^ operator
Here's the same answer but without operators.
It works only in F# 3.0 and you can use any number of parameters.
let inline i3 (a:^a,b:^b,c:^c) = ((^a or ^b or ^c) : (static member threeParams: ^a* ^b* ^c -> _) (a,b,c))
open Symbolism
type MathObjectOverloads =
| MathObjectOverloads
static member threeParams (MathObjectOverloads, a: #MathObject , b: int ) = MathObject.op_ExclusiveOr(a, b)
static member threeParams (MathObjectOverloads, a: #MathObject , b: #MathObject) = MathObject.op_ExclusiveOr(a, b)
static member threeParams (MathObjectOverloads, a: System.Int32, b: #MathObject) = MathObject.op_ExclusiveOr(a, b)
let inline ( ** ) a b = i3(MathObjectOverloads, a, b)

Resources