Skip to content

Instantly share code, notes, and snippets.

@slipset
Created March 7, 2023 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slipset/4c4e7291248b76d0d0b896d2bc737b0f to your computer and use it in GitHub Desktop.
Save slipset/4c4e7291248b76d0d0b896d2bc737b0f to your computer and use it in GitHub Desktop.
(ns area2
(:require
[clojure.math :as math]
[criterium.core :as crit]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* false)
(defprotocol IArea
(area [this]))
(require '[clj-java-decompiler.core :refer [decompile]])
(decompile
(defrecord Square [^double side]
IArea
(area [this]
(Math/pow side (double 2)))))
(defrecord Rectangle [^double width ^double height]
IArea
(area [_]
(* width height)))
(decompile (defrecord Triangle [^double base ^double height]
IArea
(area [_]
(* 0.5 base height))))
(decompile
(defrecord Circle [^double radius]
IArea
(area [this]
(* math/PI (Math/pow radius (double 2))))))
(defn make-random-shape []
(let [shapes [:square :rectangle :circle :triangle]
shape (rand-nth shapes)]
(case shape
:square (->Square (rand-int 10))
:rectangle (->Rectangle (rand-int 10) (rand-int 10))
:triangle (->Triangle (rand-int 10) (rand-int 10))
:circle (->Circle (rand-int 10)))))
(defn total-area [shapes]
(transduce (map area) + shapes))
(defn total-area [shapes]
(loop [n (double 0)
xs shapes]
(if (seq xs)
(let [s (first xs)]
(recur (+ n ^double (area s)) (rest xs)))
n)))
(defn total-area [shapes]
(reduce (fn [^double tot s]
(+ tot ^double (area s))) 0 shapes))
(def lots-of-shapes (doall (repeatedly 400000 #(make-random-shape))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment