Skip to content

user-defined eagerization #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions src/special/core.cljc
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
(ns special.core)
(ns special.core
(:require [clojure.walk :as walk]))

(defonce ^:dynamic *-special-condition-handlers-* {})

(defn- manage-with-courage
(defn- manage-eager-conditions
"Takes an eager function f and an \"inlined\" map of conditions to handlers.
Returns a function in which these conditions are managed.

Expand All @@ -24,17 +25,25 @@
(binding [*-special-condition-handlers-* (merge *-special-condition-handlers-* restarts)]
(apply f args))))

(defmulti eager (fn [type _] type))
(defmethod eager ::postwalk [_ v]
(walk/postwalk (constantly nil) v) v)
(defmethod eager ::default [_ v]
(pr-str v) v)
(defmethod eager :default [_ v]
(eager ::default v))

(defn- eagerize
"Turns a lazy function into an eager function, at the
run-time cost of using pr-str to fully realize the
function result."
[f]
[eager-method f]
(fn [& args]
(let [res (apply f args)
_ (pr-str res)]
res)))
(if (keyword? eager-method)
(eager eager-method (apply f args))
(eager-method (apply f args)) )))

(defn manage
(defn manage-as
"Takes a function f and an \"inlined\" map of conditions and keywords.
Returns a function in which these conditions are managed.

Expand All @@ -43,9 +52,15 @@

f is allowed to be lazy, but the result must be finite, as it will
always be fully realized. In other words: manage returns an eager function."
[type f & restarts]
(apply manage-eager-conditions (eagerize type f) restarts))

(defn manage-with
[eager-fn f & restarts]
(apply manage-eager-conditions (eagerize eager-fn f) restarts))

[f & restarts]
(apply manage-with-courage (eagerize f) restarts))
(def manage (partial manage-with #(do (pr-str %) %)))
;; or (def manage (partial manage-as ::default))

(defn condition
"Raise a condition c with optional value v and optionally an \"inlined\" map of conditions to handlers.
Expand Down