Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Last active November 17, 2017 19:30
Show Gist options
  • Save jackrusher/8777040 to your computer and use it in GitHub Desktop.
Save jackrusher/8777040 to your computer and use it in GitHub Desktop.
Clojure, Haskell and OCaml implementations of the same algorithm, which is a negative space finder for a very constrained situation involving nested rectangles. For those interested in a more comprehensive take on these relationships (using scheme rather than clojure), see: http://lambda.jimpryor.net/translating_between_ocaml_scheme_and_haskell/
(def parent {:x1 0 :y1 0 :x2 600 :y2 400})
(def rs [{:x1 0 :y1 0 :x2 300 :y2 200 }
{:x1 0 :y1 200 :x2 300 :y2 400 }])
(defn negative-space [parent rs]
(let [x (apply max (map :x2 rs))
y (apply min (map :y1 (filter (comp (partial = x) :x2) rs)))]
{:x1 x :y1 y :x2 (parent :x2) :y2 (parent :y2)}))
(negative-space parent rs)
-- Yes, my Haskell brothers, I know about $ and 'where',
-- but the point of this is the similarities, not a few
-- differences in syntactical sugar.
data Rectangle = Rectangle { x1, y1, x2, y2 :: Int } deriving (Eq,Show)
parent = Rectangle 0 0 600 400
rs = [Rectangle 0 300 0 200, Rectangle 0 300 200 400]
negativeSpace :: Rectangle -> [Rectangle] -> Rectangle
negativeSpace p rs =
let x = foldl max 0 (map x2 rs) in
let y = foldl min 0 (map y1 (filter ((== x) . x2) rs)) in
Rectangle x y (x2 p) (y2 p)
negativeSpace parent rs
open List;; (* it's bad style to open List, innit? *)
type rect = { x1 : int; y1 : int; x2 : int; y2 : int; };;
let parent = { x1 = 0; y1 = 0; x2 = 600; y2 = 400;}
let rs = [{ x1 = 0; x2 = 300; y1 = 0; y2 = 200; };
{ x1 = 0; x2 = 300; y1 = 200; y2 = 400; }];;
let negative_space (parent, rs) =
let x = fold_left max 0 (map (fun r -> r.x2) rs) in
let y = fold_left min 0 (map (fun r -> r.y1) (filter (fun r -> r.x2 = x) rs)) in
{ x1 = x; y1 = y; x2 = parent.x2; y2 = parent.y2; };;
let r = negative_space (parent, rs);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment