Skip to content

How do I do ADT in hy? #2392

Answered by glyh
glyh asked this question in Q&A
Jan 24, 2023 · 2 comments · 3 replies
Discussion options

You must be logged in to vote

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))
(

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@glyh
Comment options

@glyh
Comment options

@Kodiologist
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by glyh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants