I’m doing a project called “2dShapeEditor” where you are supposed to be able to create, click and drag different kind of shapes on a form. At the stage of the project I am at right now, i need to determine what kind of type my targeted rectangle is. It’s initialized as an “Option” but can through a “hittest” change to the specific rectangle that is clicked.
I will then apply my move method to this rectangle making it move with the mouse.
My type RectangleZ
type RectangleZ(x:int, y:int)=
let mutable thisx = x
let mutable thisy = y
let mutable thiswidth = 50
let mutable thisheight = 20
let brush = new SolidBrush(Color.Black)
member obj.x with get () = thisx and set x = thisx <- x
member obj.y with get () = thisy and set y = thisy <- y
member obj.width with get () = thiswidth and set width = thiswidth <- width
member obj.height with get () = thisheight and set height = thisheight <- height
member obj.thisColor = Color.FromArgb(167, 198, 253)
member obj.draw(paper:Graphics) = paper.FillRectangle(brush, thisx, thisy, 50, 20)
member obj.ShapeType = "Rectangle"
My hittest method:
let rec getShape (e:MouseEventArgs) (inputl:List<RectangleZ>) = match inputl with
|[] -> None
|s::tail->if(((e.X >= s.x) && (s.x <= (s.x + s.width))) && ((e.Y >= s.y) && (e.Y <= (s.y + s.height)))) then Some(s) else getShape e tail //Some(s)
My targeted rectangle look like this:
let mutable targetedRec = None
My “Move()” method looks like this:
let Move (e:MouseEventArgs) = if(targetedRec = None) then None else targetedRec.Value.x <- e.X
targetedRec.Value.y <- e.Y
The “Move()” method gives me the error: “Lookup on object of indeterminate type based on information prior to this
program point. A type annotation may be needed prior to this program to constrain the type of the object. This may allow the lookup to be resolved.”
And yes, the compiler gives me a hint of what’s wrong and how to fix it, i’ve tried with matching, if statements, I simply don’t understand what’s wrong and how to fix it. If I remove the Option type of the targetedRec and just put it as a type of “RectangleZ” alot of my project will fail because i can’t leave blank if statements. Any suggestions?
What type is inferred for ‘targetedRec’? (You can tell by hovering the mouse over it and looking at the Intellisense tooltip.)
From what you’ve posted, the F# compiler is only able to infer the type of ‘targetedRec’ as
'a option— that is, the compiler knows it’s an Option (because you’ve assignedNoneto it), but it can’t tell what the type parameter of the option is supposed to be. Then, you see the error in yourMovemethod because the compiler can’t tell what type thexandyfields belong to.This is pretty easy to fix though — just add a type annotation to your declaration for
targetedRec, like so:That alone should fix the problem, but you can clean up your
Movemethod a bit too by using pattern matching instead of manually checking theValueproperty: