Skip to content
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

Pick fn arity independent of written order #532

Merged
merged 2 commits into from
Feb 17, 2021
Merged
Show file tree
Hide file tree
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
25 changes: 18 additions & 7 deletions src/sci/impl/fns.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,23 @@
f)))

(defn lookup-by-arity [arities arity]
(some (fn [f]
(let [{:sci.impl/keys [fixed-arity min-var-args-arity]} (meta f)]
(when (or (= arity fixed-arity )
(and min-var-args-arity
(>= arity min-var-args-arity)))
f))) arities))
(or (get arities arity)
(let [vf (:variadic arities)
min-var-args-arity (:sci.impl/min-var-args-arity (meta vf))]
(when (and min-var-args-arity
(>= arity min-var-args-arity))
vf))))

(defn fn-arity-map [ctx interpret fn-name macro? fn-bodies]
(reduce
(fn [arity-map fn-body]
(let [f (fun ctx interpret fn-body fn-name macro? true)
{:sci.impl/keys [fixed-arity min-var-args-arity]} (meta f)]
(if min-var-args-arity
(assoc arity-map :variadic f)
(assoc arity-map fixed-arity f))))
nil
fn-bodies))

(defn eval-fn [ctx interpret {:sci.impl/keys [fn-bodies fn-name
var] :as f}]
Expand All @@ -242,7 +253,7 @@
single-arity? (= 1 (count fn-bodies))
f (if single-arity?
(fun ctx interpret (first fn-bodies) fn-name macro? false)
(let [arities (map #(fun ctx interpret % fn-name macro? true) fn-bodies)]
(let [arities (fn-arity-map ctx interpret fn-name macro? fn-bodies)]
(fn [& args]
(let [arg-count (count args)]
(if-let [f (lookup-by-arity arities arg-count)]
Expand Down
3 changes: 3 additions & 0 deletions test/sci/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@
(is (= 2 (eval* '((fn foo [x & [y]] y) 1 2 3))))
(is (= 1 (eval* '((fn ([x] x) ([x y] y)) 1))))
(is (= 2 (eval* '((fn ([x] x) ([x y] y)) 1 2))))
(is (= "otherwise" (eval* '((fn ([x & xs] "variadic") ([x] "otherwise")) 1))))
(is (= "otherwise" (eval* '((fn ([x] "otherwise") ([x & xs] "variadic")) 1))))
(is (= "variadic" (eval* '((fn ([x] "otherwise") ([x & xs] "variadic")) 1 2))))
(is (= '(2 3 4) (eval* '(apply (fn [x & xs] xs) 1 2 [3 4]))))
(is (thrown-with-msg? #?(:clj Exception :cljs js/Error)
#"Can't have fixed arity function with more params than variadic function"
Expand Down