1
$\begingroup$

I want to implement pattern matching for a few simple types. In particular, I want to define a function mirror that mirrors circles and rectangles.

That is,

mirror[Circle[{1,2},3]] == Circle[{1,-2},3]
mirror[Rectangle[{4,5},{6,7}]] == Rectangle[{4,-5},{6,-7}]

In languages such as Haskell, this is done via pattern matching:

mirror (Circle x y) = Circle x (-y)

etc. but when I tried to do the same in Mathematica, the expression did not evaluate:

mirror[obj_] := Switch[obj,
    Circle[{x, y}, r], Circle[{x,-y},r]
];

Is there a way to achieve this functionality in Mathematica?

$\endgroup$
2
  • 7
    $\begingroup$ mirror[ Circle[{x_, y_}, r_] ] := Circle[{x,-y},r] please read everything related to tutorial/Introduction-Patterns. $\endgroup$
    – Kuba
    Commented Sep 26, 2018 at 14:09
  • 1
    $\begingroup$ funny that you mention Haskell; you'll notice from Kuba's example that something completely analogous (that is, destructuring) is being used in Mathematica as well. $\endgroup$ Commented Sep 26, 2018 at 14:10

1 Answer 1

3
$\begingroup$

Instead of pattern matching, you might want to consider using TransformedRegion:

TransformedRegion[Circle[{1, 2}, 3], ReflectionTransform[{0,1}]]

Circle[{1, -2}, 3]

Making a function to do this:

reflect[primitive_] := TransformedRegion[primitive, ReflectionTransform[{0, 1}]]

Then:

reflect[Circle[{1, 2}, 3]]
reflect[Rectangle[{4, 5}, {6, 7}]]

Circle[{1, -2}, 3]

Rectangle[{4, -7}, {6, -5}]

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.