{-# LANGUAGE OverloadedStrings #-}
{- |
   Module      : Text.Pandoc.Readers.Xlsx.Sheets
   Copyright   : © 2025 Anton Antic
   License     : GNU GPL, version 2 or above

   Maintainer  : Anton Antic <anton@everworker.ai>
   Stability   : alpha
   Portability : portable

Conversion of XLSX sheets to Pandoc AST.
-}
module Text.Pandoc.Readers.Xlsx.Sheets
  ( xlsxToOutput
  ) where

import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.List (sort, dropWhileEnd)
import Numeric (floatToDigits)
import Data.Char (isSpace)
import Text.Pandoc.Definition
import Text.Pandoc.Options (ReaderOptions)
import Text.Pandoc.Readers.OOXML.Charts (chartToBlocks)
import Text.Pandoc.Readers.Xlsx.Parse
import Text.Pandoc.Readers.Xlsx.Cells
import qualified Text.Pandoc.Builder as B

-- | Convert XLSX to Pandoc output
xlsxToOutput :: ReaderOptions -> Xlsx -> (Meta, [Block])
xlsxToOutput :: ReaderOptions -> Xlsx -> (Meta, [Block])
xlsxToOutput ReaderOptions
_opts Xlsx
xlsx =
  let sheets :: [XlsxSheet]
sheets = Xlsx -> [XlsxSheet]
xlsxSheets Xlsx
xlsx
      sheetBlocks :: [Block]
sheetBlocks = (XlsxSheet -> [Block]) -> [XlsxSheet] -> [Block]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap XlsxSheet -> [Block]
sheetToBlocks [XlsxSheet]
sheets
   in (Meta
forall a. Monoid a => a
mempty, [Block]
sheetBlocks)

-- | Convert sheet to blocks (header + table)
sheetToBlocks :: XlsxSheet -> [Block]
sheetToBlocks :: XlsxSheet -> [Block]
sheetToBlocks XlsxSheet
sheet =
  let SheetId Int
n = XlsxSheet -> SheetId
sheetId XlsxSheet
sheet
      name :: Text
name = XlsxSheet -> Text
sheetName XlsxSheet
sheet
      sheetIdent :: Text
sheetIdent = Text
"sheet-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Int -> String
forall a. Show a => a -> String
show Int
n)
      header :: Block
header = Int -> Attr -> [Inline] -> Block
Header Int
2 (Text
sheetIdent, [], []) (Many Inline -> [Inline]
forall a. Many a -> [a]
B.toList (Text -> Many Inline
B.text Text
name))

      -- Convert cells to table
      tableBlock :: [Block]
tableBlock = case XlsxSheet -> Maybe Block
cellsToTable XlsxSheet
sheet of
        Just Block
tbl -> [Block
tbl]
        Maybe Block
Nothing -> []  -- Empty sheet
   in Block
header Block -> [Block] -> [Block]
forall a. a -> [a] -> [a]
: [Block]
tableBlock [Block] -> [Block] -> [Block]
forall a. [a] -> [a] -> [a]
++ (Chart -> [Block]) -> [Chart] -> [Block]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Chart -> [Block]
chartToBlocks (XlsxSheet -> [Chart]
sheetCharts XlsxSheet
sheet)

-- | Convert cells to Pandoc Table
cellsToTable :: XlsxSheet -> Maybe Block
cellsToTable :: XlsxSheet -> Maybe Block
cellsToTable XlsxSheet
sheet
  | Map CellRef XlsxCell -> Bool
forall k a. Map k a -> Bool
M.null (XlsxSheet -> Map CellRef XlsxCell
sheetCells XlsxSheet
sheet) = Maybe Block
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let cells :: Map CellRef XlsxCell
cells = XlsxSheet -> Map CellRef XlsxCell
sheetCells XlsxSheet
sheet
          -- Get bounds
          refs :: [CellRef]
refs = [CellRef] -> [CellRef]
forall a. Ord a => [a] -> [a]
sort ([CellRef] -> [CellRef]) -> [CellRef] -> [CellRef]
forall a b. (a -> b) -> a -> b
$ Map CellRef XlsxCell -> [CellRef]
forall k a. Map k a -> [k]
M.keys Map CellRef XlsxCell
cells
          minCol :: Int
minCol = [Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
minimum ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (CellRef -> Int) -> [CellRef] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map CellRef -> Int
cellRefCol [CellRef]
refs
          maxCol :: Int
maxCol = [Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (CellRef -> Int) -> [CellRef] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map CellRef -> Int
cellRefCol [CellRef]
refs
          minRow :: Int
minRow = [Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
minimum ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (CellRef -> Int) -> [CellRef] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map CellRef -> Int
cellRefRow [CellRef]
refs
          maxRow :: Int
maxRow = [Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum ([Int] -> Int) -> [Int] -> Int
forall a b. (a -> b) -> a -> b
$ (CellRef -> Int) -> [CellRef] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map CellRef -> Int
cellRefRow [CellRef]
refs

          -- Build dense grid
          grid :: [[(CellRef, Maybe XlsxCell)]]
grid = [ [ (Int -> Int -> CellRef
CellRef Int
col Int
row, CellRef -> Map CellRef XlsxCell -> Maybe XlsxCell
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Int -> Int -> CellRef
CellRef Int
col Int
row) Map CellRef XlsxCell
cells)
                   | Int
col <- [Int
minCol..Int
maxCol]
                   ]
                 | Int
row <- [Int
minRow..Int
maxRow]
                 ]

          -- First row is header (simple heuristic)
          ([(CellRef, Maybe XlsxCell)]
headerRow, [[(CellRef, Maybe XlsxCell)]]
bodyRows) = case [[(CellRef, Maybe XlsxCell)]]
grid of
            ([(CellRef, Maybe XlsxCell)]
h:[[(CellRef, Maybe XlsxCell)]]
bs) -> ([(CellRef, Maybe XlsxCell)]
h, [[(CellRef, Maybe XlsxCell)]]
bs)
            [] -> ([], [])

          -- Filter out trailing empty rows (rows with only whitespace)
          filteredBodyRows :: [[(CellRef, Maybe XlsxCell)]]
filteredBodyRows = ([(CellRef, Maybe XlsxCell)] -> Bool)
-> [[(CellRef, Maybe XlsxCell)]] -> [[(CellRef, Maybe XlsxCell)]]
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd ([Maybe XlsxCell] -> Bool
isEmptyRow ([Maybe XlsxCell] -> Bool)
-> ([(CellRef, Maybe XlsxCell)] -> [Maybe XlsxCell])
-> [(CellRef, Maybe XlsxCell)]
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((CellRef, Maybe XlsxCell) -> Maybe XlsxCell)
-> [(CellRef, Maybe XlsxCell)] -> [Maybe XlsxCell]
forall a b. (a -> b) -> [a] -> [b]
map (CellRef, Maybe XlsxCell) -> Maybe XlsxCell
forall a b. (a, b) -> b
snd) [[(CellRef, Maybe XlsxCell)]]
bodyRows
          lastRow :: Int
lastRow = Int
minRow Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [[(CellRef, Maybe XlsxCell)]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[(CellRef, Maybe XlsxCell)]]
filteredBodyRows

          -- A merged range becomes one cell spanning its rows and
          -- columns, clipped to the table and kept within the header row
          -- or within the body, as a cell can't span both.
          spans :: Map CellRef (Int, Int)
spans = [(CellRef, (Int, Int))] -> Map CellRef (Int, Int)
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
            [ (CellRef
from, (Int
rows, Int
cols))
            | (CellRef
from, CellRef
to) <- XlsxSheet -> [(CellRef, CellRef)]
sheetMerges XlsxSheet
sheet
            , CellRef -> Int
cellRefCol CellRef
from Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
minCol, CellRef -> Int
cellRefCol CellRef
from Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
maxCol
            , CellRef -> Int
cellRefRow CellRef
from Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
minRow, CellRef -> Int
cellRefRow CellRef
from Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
lastRow
            , let rows :: Int
rows = if CellRef -> Int
cellRefRow CellRef
from Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
minRow
                            then Int
1
                            else Int -> Int -> Int
forall a. Ord a => a -> a -> a
min (CellRef -> Int
cellRefRow CellRef
to) Int
lastRow
                                   Int -> Int -> Int
forall a. Num a => a -> a -> a
- CellRef -> Int
cellRefRow CellRef
from Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
                  cols :: Int
cols = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min (CellRef -> Int
cellRefCol CellRef
to) Int
maxCol Int -> Int -> Int
forall a. Num a => a -> a -> a
- CellRef -> Int
cellRefCol CellRef
from Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
            , Int
rows Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1 Bool -> Bool -> Bool
|| Int
cols Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1
            ]
          covered :: Set CellRef
covered = [CellRef] -> Set CellRef
forall a. Ord a => [a] -> Set a
S.fromList
            [ Int -> Int -> CellRef
CellRef Int
col Int
row
            | (CellRef Int
c Int
r, (Int
rows, Int
cols)) <- Map CellRef (Int, Int) -> [(CellRef, (Int, Int))]
forall k a. Map k a -> [(k, a)]
M.toList Map CellRef (Int, Int)
spans
            , Int
row <- [Int
r .. Int
r Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
rows Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], Int
col <- [Int
c .. Int
c Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
cols Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
            , (Int
col, Int
row) (Int, Int) -> (Int, Int) -> Bool
forall a. Eq a => a -> a -> Bool
/= (Int
c, Int
r)
            ]

          makeCell :: (CellRef, Maybe XlsxCell) -> Cell
makeCell (CellRef
ref, Maybe XlsxCell
mcell) =
            let (Int
rows, Int
cols) = (Int, Int) -> CellRef -> Map CellRef (Int, Int) -> (Int, Int)
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault (Int
1, Int
1) CellRef
ref Map CellRef (Int, Int)
spans
             in Attr -> Alignment -> RowSpan -> ColSpan -> [Block] -> Cell
Cell Attr
nullAttr Alignment
AlignDefault (Int -> RowSpan
RowSpan Int
rows) (Int -> ColSpan
ColSpan Int
cols)
                     [[Inline] -> Block
Plain ([Inline] -> (XlsxCell -> [Inline]) -> Maybe XlsxCell -> [Inline]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] XlsxCell -> [Inline]
cellToInlines Maybe XlsxCell
mcell)]
          makeRow :: [(CellRef, Maybe XlsxCell)] -> Row
makeRow = Attr -> [Cell] -> Row
Row Attr
nullAttr ([Cell] -> Row)
-> ([(CellRef, Maybe XlsxCell)] -> [Cell])
-> [(CellRef, Maybe XlsxCell)]
-> Row
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((CellRef, Maybe XlsxCell) -> Cell)
-> [(CellRef, Maybe XlsxCell)] -> [Cell]
forall a b. (a -> b) -> [a] -> [b]
map (CellRef, Maybe XlsxCell) -> Cell
makeCell ([(CellRef, Maybe XlsxCell)] -> [Cell])
-> ([(CellRef, Maybe XlsxCell)] -> [(CellRef, Maybe XlsxCell)])
-> [(CellRef, Maybe XlsxCell)]
-> [Cell]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                    ((CellRef, Maybe XlsxCell) -> Bool)
-> [(CellRef, Maybe XlsxCell)] -> [(CellRef, Maybe XlsxCell)]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(CellRef
ref, Maybe XlsxCell
_) -> Bool -> Bool
not (CellRef
ref CellRef -> Set CellRef -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CellRef
covered))

          numCols :: Int
numCols = [(CellRef, Maybe XlsxCell)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(CellRef, Maybe XlsxCell)]
headerRow
          colSpec :: [(Alignment, ColWidth)]
colSpec = Int -> (Alignment, ColWidth) -> [(Alignment, ColWidth)]
forall a. Int -> a -> [a]
replicate Int
numCols (Alignment
AlignDefault, ColWidth
ColWidthDefault)
          thead :: TableHead
thead = Attr -> [Row] -> TableHead
TableHead Attr
nullAttr [[(CellRef, Maybe XlsxCell)] -> Row
makeRow [(CellRef, Maybe XlsxCell)]
headerRow]
          tbody :: [TableBody]
tbody = [Attr -> RowHeadColumns -> [Row] -> [Row] -> TableBody
TableBody Attr
nullAttr RowHeadColumns
0 [] ([Row] -> TableBody) -> [Row] -> TableBody
forall a b. (a -> b) -> a -> b
$ ([(CellRef, Maybe XlsxCell)] -> Row)
-> [[(CellRef, Maybe XlsxCell)]] -> [Row]
forall a b. (a -> b) -> [a] -> [b]
map [(CellRef, Maybe XlsxCell)] -> Row
makeRow [[(CellRef, Maybe XlsxCell)]]
filteredBodyRows]
          tfoot :: TableFoot
tfoot = Attr -> [Row] -> TableFoot
TableFoot Attr
nullAttr []

       in Block -> Maybe Block
forall a. a -> Maybe a
Just (Block -> Maybe Block) -> Block -> Maybe Block
forall a b. (a -> b) -> a -> b
$ Attr
-> Caption
-> [(Alignment, ColWidth)]
-> TableHead
-> [TableBody]
-> TableFoot
-> Block
Table Attr
nullAttr (Maybe [Inline] -> [Block] -> Caption
Caption Maybe [Inline]
forall a. Maybe a
Nothing []) [(Alignment, ColWidth)]
colSpec TableHead
thead [TableBody]
tbody TableFoot
tfoot

-- | Check if a row contains only whitespace or empty cells
isEmptyRow :: [Maybe XlsxCell] -> Bool
isEmptyRow :: [Maybe XlsxCell] -> Bool
isEmptyRow = (Maybe XlsxCell -> Bool) -> [Maybe XlsxCell] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Maybe XlsxCell -> Bool
isEmptyCell
  where
    isEmptyCell :: Maybe XlsxCell -> Bool
isEmptyCell Maybe XlsxCell
Nothing = Bool
True
    isEmptyCell (Just XlsxCell
cell) = case XlsxCell -> CellValue
cellValue XlsxCell
cell of
      CellValue
EmptyValue -> Bool
True
      TextValue Text
t -> (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isSpace Text
t
      NumberValue Double
_ -> Bool
False
      BoolValue Bool
_ -> Bool
False

-- | Convert cell to Pandoc inlines
cellToInlines :: XlsxCell -> [Inline]
cellToInlines :: XlsxCell -> [Inline]
cellToInlines XlsxCell
cell =
  let base :: [Inline]
base = case XlsxCell -> CellValue
cellValue XlsxCell
cell of
        TextValue Text
t -> Many Inline -> [Inline]
forall a. Many a -> [a]
B.toList (Many Inline -> [Inline]) -> Many Inline -> [Inline]
forall a b. (a -> b) -> a -> b
$ Text -> Many Inline
B.text Text
t
        NumberValue Double
n -> [Text -> Inline
Str (Text -> Inline) -> Text -> Inline
forall a b. (a -> b) -> a -> b
$ Double -> Text
formatGeneral Double
n]
        BoolValue Bool
b -> [Text -> Inline
Str (Text -> Inline) -> Text -> Inline
forall a b. (a -> b) -> a -> b
$ if Bool
b then Text
"TRUE" else Text
"FALSE"]
        CellValue
EmptyValue -> []

      applyBold :: [Inline] -> [Inline]
applyBold [Inline]
inls = if XlsxCell -> Bool
cellBold XlsxCell
cell then [[Inline] -> Inline
Strong [Inline]
inls] else [Inline]
inls
      applyItalic :: [Inline] -> [Inline]
applyItalic [Inline]
inls = if XlsxCell -> Bool
cellItalic XlsxCell
cell then [[Inline] -> Inline
Emph [Inline]
inls] else [Inline]
inls

   in [Inline] -> [Inline]
applyItalic ([Inline] -> [Inline]) -> [Inline] -> [Inline]
forall a b. (a -> b) -> a -> b
$ [Inline] -> [Inline]
applyBold [Inline]
base

-- | Render a number as Excel's General format does, without rounding
-- it to fit a column: at most 15 significant digits (Excel's precision)
-- and no trailing zeros. Numbers with 12 or more digits before the
-- decimal point use scientific notation (@1.23456789012E+11@), as General
-- does, keeping all their digits; so do numbers below 1e-9.
formatGeneral :: Double -> T.Text
formatGeneral :: Double -> Text
formatGeneral Double
x
  | Double -> Bool
forall a. RealFloat a => a -> Bool
isNaN Double
x Bool -> Bool -> Bool
|| Double -> Bool
forall a. RealFloat a => a -> Bool
isInfinite Double
x = String -> Text
T.pack (Double -> String
forall a. Show a => a -> String
show Double
x)
  | Double
x Double -> Double -> Bool
forall a. Eq a => a -> a -> Bool
== Double
0 = Text
"0"
  | Bool
otherwise = String -> Text
T.pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ String
sign String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
body
  where
    sign :: String
sign = if Double
x Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
< Double
0 then String
"-" else String
""
    ([Int]
ds, Int
e) = Int -> ([Int], Int) -> ([Int], Int)
roundDigits Int
15 (Integer -> Double -> ([Int], Int)
forall a. RealFloat a => Integer -> a -> ([Int], Int)
floatToDigits Integer
10 (Double -> Double
forall a. Num a => a -> a
abs Double
x))
    digits :: String
digits = (Int -> String) -> [Int] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Int -> String
forall a. Show a => a -> String
show [Int]
ds
    -- abs x == 0.d1d2d3... * 10^e
    body :: String
body
      | Int
e Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
11 Bool -> Bool -> Bool
|| Int
e Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< -Int
8 = String
scientific
      | Int
e Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = String
"0." String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> Char -> String
forall a. Int -> a -> [a]
replicate (Int -> Int
forall a. Num a => a -> a
negate Int
e) Char
'0' String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
digits
      | [Int] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Int]
ds Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
e = String
digits String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> Char -> String
forall a. Int -> a -> [a]
replicate (Int
e Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Int] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Int]
ds) Char
'0'
      | Bool
otherwise = Int -> String -> String
forall a. Int -> [a] -> [a]
take Int
e String
digits String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"." String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String -> String
forall a. Int -> [a] -> [a]
drop Int
e String
digits
    scientific :: String
scientific =
      let mantissa :: String
mantissa = case String
digits of
            Char
d:rest :: String
rest@(Char
_:String
_) -> Char
d Char -> String -> String
forall a. a -> [a] -> [a]
: Char
'.' Char -> String -> String
forall a. a -> [a] -> [a]
: String
rest
            String
_ -> String
digits
          ex :: Int
ex = Int
e Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1
       in String
mantissa String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"E" String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if Int
ex Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 then String
"-" else String
"+") String -> String -> String
forall a. [a] -> [a] -> [a]
++
          (let a :: String
a = Int -> String
forall a. Show a => a -> String
show (Int -> Int
forall a. Num a => a -> a
abs Int
ex) in if String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
a Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 then Char
'0' Char -> String -> String
forall a. a -> [a] -> [a]
: String
a else String
a)

-- | Round a digit list (as from 'floatToDigits') to at most n digits,
-- dropping trailing zeros.
roundDigits :: Int -> ([Int], Int) -> ([Int], Int)
roundDigits :: Int -> ([Int], Int) -> ([Int], Int)
roundDigits Int
n ([Int]
ds, Int
e) =
  case Int -> [Int] -> ([Int], [Int])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
n [Int]
ds of
    ([Int]
_, []) -> ([Int]
ds, Int
e)
    ([Int]
keep, Int
d:[Int]
_) ->
      case if Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
5 then [Int] -> Maybe [Int]
forall {a}. (Eq a, Num a) => [a] -> Maybe [a]
carry ([Int] -> [Int]
forall a. [a] -> [a]
reverse [Int]
keep) else [Int] -> Maybe [Int]
forall a. a -> Maybe a
Just [Int]
keep of
        Just [Int]
ds' -> ((Int -> Bool) -> [Int] -> [Int]
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0) [Int]
ds', Int
e)
        Maybe [Int]
Nothing -> ([Int
1], Int
e Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
  where
    -- Add one to a reversed digit list; Nothing if it overflows (all 9s).
    carry :: [a] -> Maybe [a]
carry [] = Maybe [a]
forall a. Maybe a
Nothing
    carry (a
9:[a]
rest) = ([a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a
0]) ([a] -> [a]) -> Maybe [a] -> Maybe [a]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [a] -> Maybe [a]
carry [a]
rest
    carry (a
k:[a]
rest) = [a] -> Maybe [a]
forall a. a -> Maybe a
Just ([a] -> [a]
forall a. [a] -> [a]
reverse (a
k a -> a -> a
forall a. Num a => a -> a -> a
+ a
1 a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
rest))