How do I do ADT in hy?
#2392
-
Here's a link of how do you do ADT in python. I'm aware of we have match, but how would you implement a recursive tree with it? |
Beta Was this translation helpful? Give feedback.
Answered by
glyh
Jan 24, 2023
Replies: 2 comments 3 replies
-
We've supported Python 3.11 for a while, so you can translate any of those examples to Hy in a literal fashion and the effect should be the same. |
Beta Was this translation helpful? Give feedback.
3 replies
-
I figured it out, something is not well-documented, but here's the final code for ADT example on SO: (import dataclasses [dataclass])
(defclass [dataclass] Point []
(annotate x float)
(annotate y float))
(defclass [dataclass] Circle []
(annotate x float)
(annotate y float)
(annotate r float))
(defclass [dataclass] Rectangle []
(annotate x float)
(annotate y float)
(annotate w float)
(annotate h float))
(setv Shape (| Point Circle Rectangle))
(defn print-shape [#^Shape shape]
(match shape
(Point x y) (print f"Point {x} {y}")
(Circle x y r) (print f"Circle {x} {y} {r}")
(Rectangle x y w h) (print f"Circle {x} {y} {w} {h}")))
(print-shape (Point 1 2))
(print-shape (Circle 3 5 7))
(print-shape (Rectangle 11 13 17 19))
(print-shape 4) I would say, though, it's kinda ugly. so I may write a macro for this. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
glyh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I figured it out, something is not well-documented, but here's the final code for ADT example on SO: