2

I am trying to get the rounded off version of a list of numerics in Clojure.

For e.g. (Math/round 10.5) gives me 11 as the answer which is fine. However, I try a similar approach using 'apply' - (apply Math/round (list 1.2 2.1 3.4)) which gives me an error. I was expecting (1 2 3) as the output.

How to get a rounded off output from a list of numbers?

honeybadger
  • 1,465
  • 1
  • 19
  • 32
  • @JaredSmith: I am a newbie to Clojure. I was blindly following this: https://stackoverflow.com/questions/28551000/what-is-the-best-way-to-round-numbers-in-clojure – honeybadger Sep 24 '18 at 19:54
  • Nevermind my earlier comment, it's the same interop for both. – Jared Smith Sep 24 '18 at 19:58

1 Answers1

4

Use map. Note that you'll have to wrap the call to Math/round in an anonymous function: see this question for the reason why.

(map #(Math/round %) (list 1.1 2.2 3.9)) ; '(1 2 4)

The problem with your approach (which was actually not a bad guess) is that Java's Math/round isn't variadic: it just takes a single argument. Calling apply that way is the same as saying

(Math/round 1.2 2.1 3.4)

Which will fail to compile.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83