Destructuring and Function Overloading #2537
-
I've noticed there is no destructuring like Clojure.. or there was but now there aren't? (defn process-data
([] (println "No data provided"))
([status-keyword]
(cond
(= :success status-keyword) (println "Operation completed successfully")
(= :error status-keyword) (println "Error occurred")
:else (println "Unknown status")))
([status-keyword message]
(cond
(= :success status-keyword) (println "Operation completed successfully with message:" message)
(= :error status-keyword) (println "Error occurred with message:" message)
:else (println "Unknown status"))))
;; Example usage
(process-data)
(process-data :success)
Can it be done as simply in Hy? If not, this is a pretty big deal for me deciding to adopt this language. I'm coming from the Erlang Pattern matching side of things, and I just don't know the Hy equivalent. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hy doesn't (natively) have function overloading like that, but—just as you can with Python—you can implement something similar by using Python's own match/destructuring: (require hyrule [case])
(defn process-data [#* args]
(match args
[] (print "No data provided")
["success"] (print "Operation completed successfully")
["error"] (print "Error occurred")
[_] (print "Unknown status")
[status-keyword message]
(case status-keyword
"success" (print "Operation completed successfully with message:" message)
"error" (print "Error occurred with message:" message)
else (print "Unknown status"))))
;; Example usage
(process-data)
(process-data "success") ( |
Beta Was this translation helpful? Give feedback.
-
There's also some fancier destructuring macros in Hyrule. |
Beta Was this translation helpful? Give feedback.
Hy doesn't (natively) have function overloading like that, but—just as you can with Python—you can implement something similar by using Python's own match/destructuring: