From 14b8c850a92ec30889f388361ed95843a46d55c8 Mon Sep 17 00:00:00 2001 From: Jaro Date: Sun, 4 Jun 2023 06:05:10 +0200 Subject: [PATCH] Implement unions of lists of rectangles. --- .../Text/ParagraphLayout/Internal/Rect.hs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/Data/Text/ParagraphLayout/Internal/Rect.hs b/src/Data/Text/ParagraphLayout/Internal/Rect.hs index ec5b9cd..880116d 100644 --- a/src/Data/Text/ParagraphLayout/Internal/Rect.hs +++ b/src/Data/Text/ParagraphLayout/Internal/Rect.hs @@ -5,6 +5,8 @@ module Data.Text.ParagraphLayout.Internal.Rect , Rect (Rect, x_origin, y_origin, x_size, y_size) , height , union + , unionMany + , unionMany1 , width , x_max , x_min @@ -15,6 +17,8 @@ module Data.Text.ParagraphLayout.Internal.Rect ) where +import Data.List.NonEmpty (NonEmpty, nonEmpty) + -- | An axis-aligned rectangle on a 2D plane. data Rect a = Rect { x_origin :: a @@ -101,3 +105,21 @@ union bias a b = hy = y_max a `max` y_max b dx = hx - lx dy = hy - ly + +-- | `Just` the `union` of all given rectangles, or `Nothing` if none are given. +unionMany :: (Num a, Ord a) => Bias -> [Rect a] -> Maybe (Rect a) +unionMany bias rects = unionMany1 bias <$> nonEmpty rects + +-- | The `union` of all given rectangles, where at least one must be given. +-- +-- Note that adding a default value to the input list to make it non-empty +-- will probably not do what you want, since the `union` operation has no +-- identity element. +-- +-- If you need a default output value for empty inputs, consider using: +-- +-- @ +-- `Data.Maybe.fromMaybe` yourDefaultValue $ `unionMany` bias rects +-- @ +unionMany1 :: (Num a, Ord a) => Bias -> NonEmpty (Rect a) -> Rect a +unionMany1 bias rects = foldr1 (union bias) rects -- 2.30.2