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

Expose functions for custom arithmetic fn #10

Closed
Frozenlock opened this issue Jan 14, 2024 · 3 comments
Closed

Expose functions for custom arithmetic fn #10

Frozenlock opened this issue Jan 14, 2024 · 3 comments

Comments

@Frozenlock
Copy link
Contributor

I have a safe-divide function returning ##Inf when dividing by zero.

(defn safe-divide [a b]
  (if (zero? b)
    (if (neg? a)
      ##-Inf
      ##Inf)
    (/ a b)))

I'd like to have a version working with broch, but boxed-arithmetic only accepts a few functions from clojure.core.
I understand the logic behind that, but unfortunately writing my own custom boxed-arithmetic turns out to be quite difficult as most of the used functions are private.

Would it be possible to expose those functions?

Alternatively, perhaps boxed-arithmetic could expose two sub-functions where the user could do the dispatch manually?
Something like boxed-mult-div and boxed-add-sub-min-max.

@2food
Copy link
Contributor

2food commented Jan 15, 2024

Hmm, I think you can get a version of your safe-divide for broch quantities using b/with-num to get the right unit for the given division (with 1/1 so it's a safe division) and then set the number to either ##Inf or ##-Inf.

(defn div-derive [a b]
  (b// (b/with-num a 1) (b/with-num b 1)))

(defn safe-divide-b [a b]
  (if (zero? (b/num b))
    (let [inf (if (neg? (b/num a)) ##-Inf ##Inf)]
      (b/with-num (div-derive a b) inf))
    (b// a b)))

(comment
  (safe-divide-b (b/meters 1) (b/seconds 0))                ; => #broch/quantity[##Inf "m/s"]
  (safe-divide-b (b/meters -1) (b/seconds 0))               ; => #broch/quantity[##-Inf "m/s"]
  )

@2food
Copy link
Contributor

2food commented Jan 15, 2024

Does this cover your use-case?

@Frozenlock
Copy link
Contributor Author

With a slight modification to div-derive to handle cases where a and/or b are numbers, it does!

(defn div-derive [a b]
  (b// (if (number? a)
         1
         (b/with-num a 1))
       (if (number? b)
         1
         (b/with-num b 1))))

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants