5

I have a following sample of code:

(type (apply / [5.0 0]))

It throws an unexpected error - "Division By Zero" (expected behavior: return Inf)

Probably, it happens due to auto-boxing - can it be prevented?

ischenko
  • 81
  • 1
  • 4
  • What does this have to do with boxing at all? It's just a division by zero - which is undefined in math. Or am I missing something? – Just another Java programmer Apr 24 '22 at 05:41
  • 1
    `(/ 5.0 0)` returns `##Inf`. I think OP is looking for some version of `apply` which returns the same result. – Martin Půda Apr 24 '22 at 06:06
  • @JustanotherJavaprogrammer Java follows the IEEE 754 standard- see Exception handling, division by zero. https://en.wikipedia.org/wiki/IEEE_754#Exception_handling – Martin Půda Apr 24 '22 at 06:19
  • 3
    Seems like a Clojure inconsistency (if not a bug).See https://clojure.atlassian.net/browse/CLJ-2244 and https://clojure.atlassian.net/browse/CLJ-1142 – dorab Apr 24 '22 at 16:28
  • 1
    See [this answer with Clojure High Performance Programming suggestions](https://stackoverflow.com/a/20455645/2609980) and as also mentioned by dorab the [clj-commons/primitive-math](https://github.com/clj-commons/primitive-math) with "equivalents for every arithmetic operator and comparator that will give a reflection warning if it cannot compile down to a simple, predictable, unboxed mathematical operation". – user2609980 Apr 25 '22 at 13:26

2 Answers2

1

Assuming you just want to use a two argument division on doubles, the following might work.

user=> (apply (fn d2div [n d] (double (/ (double n) (double d)))) [5.0 0.0])
##Inf

If you go down this path, check out clj-cmmons/primitive-math.

dorab
  • 807
  • 5
  • 13
-1

How about

user=> (defmacro myapply [func args] `(~func ~@args))
#'user/myapply
user=> (myapply / [5.0 0])
##Inf
user=> (type (myapply / [5.0 0]))
java.lang.Double

I didn't know that apply behaves in such a different manner in Clojure.

Gwang-Jin Kim
  • 9,303
  • 17
  • 30
  • This macro is useless. It only works for literal vectors, i.e. when you could have just written `(/ x y)` to begin with. It can't work for actual list variables, which is the point of apply. – amalloy Apr 24 '22 at 19:37
  • What you mean with `list variables`? `(myapply / (5.0 0))` ? It works with it too. – Gwang-Jin Kim Apr 25 '22 at 17:31
  • @amalloy - this `myapply` works at least exactly as the OA expects it to behave ... – Gwang-Jin Kim Apr 25 '22 at 17:33
  • 1
    Ah I see - you mean an `apply` with evaluation of its arguments ... – Gwang-Jin Kim Apr 25 '22 at 17:35
  • 1
    Right. Anytime someone can call your macro, it must mean they have separate expressions for all N arguments already. If they have that, they could just write `(f x y z)` themselves, instead of `(myapply f [x y z])`. – amalloy Apr 26 '22 at 03:11