Last active
October 15, 2024 10:38
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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