Can you pattern match on structs

I assume the answer is “you can’t” because I couldn’t get anything to work, and there are no examples I could get google to find.

Then the question is … why not?

My tendency was to go for structs because I have that idea in my toolkit, but I’m starting to think structs are for a special cases, being for optimising … ?


Can you clarify what you mean by “struct”? I’m able to pattern match on a struct the same way as if it weren’t a struct:

type point =
    val x : int
    val y : int
  new(a,b) = 
      x = a
      y = b

let p = point(1,2)
let q = point(2,1)

match p with
| point(1,2) -> printf "yes it matched\n"
| _          -> printf "No it didn't"

gives error

/home/jon/fsharp/test1/Program.fs(16,3): error FS0039: The pattern discriminator 'point' is not defined. [/home/jon/fsharp/test1/test1.fsproj]

The build failed. Fix the build errors and run again.

Here, this will work

You could also provide an annotation if needed:

match p with
| ({x=1; y=2} : point) -> ...

Or if you really like the syntax that you had, you could make an “Active Pattern” for it:

let (|Point|) (pt:point) = (pt.x, pt.y)

match p with
| Point(1, 2) -> ...

(Active Patterns have to start with an uppercase letter though).