It is even worse:

type MyEnum =
| A = 1
| B = 2

/// Type inference says: x : Expr<MyEnum>
let x = <@ MyEnum.A @>

leads to an runtime error:

System.ArgumentException was unhandled
Message=Type mismatch when building 'expr': the expression has the wrong type. Expected 'Program+MyEnum', but received type 'System.Int32'.
Parametername: receivedType
Source=FSharp.Core
ParamName=receivedType
StackTrace:
bei Microsoft.FSharp.Quotations.PatternsModule.checkTypesSR[a](Type expectedType, Type receivedType, a name, String threeHoleSR)
bei Microsoft.FSharp.Quotations.PatternsModule.cast[T](FSharpExpr expr)
bei Microsoft.FSharp.Quotations.FSharpExpr.Cast[T](FSharpExpr source)
...

Regards,
forki

By on 1/7/2010 6:58 AM ()

I'm not sure if it'll help you, but using a discriminated union in lieu of an enumeration works just fine.

1
2
3
4
5
6
type MyUnion = A | B

let y = <@ A @> 

// val y : Quotations.Expr<MyUnion> = NewUnionCase (MyUnion.A)
By on 1/7/2010 8:34 AM ()

Hi pblasucci,

I'm working in FunctionalNHibernate and need to map my enum values to specific ints, so using Unions unfortunately doesn't work for me.

But @aChrisSmith told me on Twitter:
"Quoting enums was is broken, it has since been fixed in our internal bits. To workaround try <@ enum<MyEnum>(int MyEnum.A) @>;;"

It's nice to hear that this is fixed. But I tried the workaround:

type MyEnum =

| A = 1

| B = 2

let x = <@ enum<myenum><MyEnum>(int MyEnum.A) @>

// x is now
// {Call (None, MyEnum ToEnum[MyEnum](Int32),
// [Call (None, Int32 ToInt[MyEnum](MyEnum), [Value (1)])])}

x.ToLinqExpression()

But now I get an error during the LINQ conversion.

System.ArgumentException was unhandled.
Expression of Typ "System.Int32" cannot be used as parameter for "MyEnum" in Int32 ToInt[MyEnum](MyEnum).

And this makes sense, because we are using a type conversion function with the wrong type. So let's try it with boxing and unboxing:
</myenum>
<myenum>let x = <@ enum<MyEnum>(MyEnum.A :> obj :?> int) @></myenum>

This seems to work but it looks really really ugly ;-)

<myenum>Regars,
forki
</myenum>

By on 1/8/2010 12:34 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper