F# FS0001: This Expression was expected to have type figure, but her has type int*int

Viewed 122

I am currently working on a program that is supposed to take a 'figure' and move it along a vector. For this I have created the function 'move' which takes a 'figure' and a vector. I am then trying to use pattern-matching to update the values of the figure.

type point = (int*int)
type figure =
 |Circle of point * int * string
 |Rectangle of point * point * string
 |Mix of figure * figure 

let circ = Circle((50,50),45,"Red")
let rect = Rectangle((40,40),(90,110),"Blue")
let figTest : figure = Mix(circ,rect)

I have the above types and the starting figure, 'figTest'. I then call 'move figTest', but it gives the error FS0001: This expression was expected to have type 'figure' but here has type 'int * int -> figure'.

let rec move figure (v:int*int) : figure= 
 let vx = fst v
 let vy = snd v
 
 match figure with
 | Circle ((cx,cy) , radius, colour) -> Circle(point(cx + vx, cy-vy), radius, colour)
 | Rectangle((x0,y0), (x1,y1), colour) -> Rectangle(point(x0 + vx, y0 + vy),point(x1 + vx, y1 + vy), colour)
 | Mix(f1,f2) ->
     let newCirc = move(f1)
     let newRect = move(f2)
     let newFig = Mix(newCirc, newRect)
     newFig

The error seems to occur when i give 'newFig' the new circle and rectangle, but I can't quite figure out what is wrong. I struggle quite a bit with these type errors in f# pretty often, so I thought I was getting the hang of it, but I just can't find the cause of this...

1 Answers

This is very close to working, so don't get discouraged. There are two minor problems:

  1. When you call move recursively, you have to pass v again. So let newCirc = move f1 v is correct instead of let newCirc = move(f1). (Note that newCirc might not actually be a circle, so you might want to use a different variable name.)

  2. Since point is just a synonym for int * int, it doesn't have its own constructor function. So (cx + vx, cy-vy) is correct instead of point(cx + vx, cy-vy).

When I made these two changes, your code worked correctly for me. There are a number of other issues with your code that you might want to address, but those are the only two that are show-stoppers at this point.

Related