Skip to content

Usage of Natural for RowIndex and ColumnIndex #200

Description

@nitinprakash96

I don't know if this has come up before but it seems that RowIndex and ColumnIndex can be misused. Eg:

ghci> columnIndexToText $ ColumnIndex (1)
"A"

ghci> columnIndexToText $ ColumnIndex (-1)
"
^?^?^?^CInterrupted.  # Hangs indefintely

Same goes for RowIndex. The behaviour is expected since both these types are Int. But I don't think this is ideal as it can lead to bugs.

I think Natural should be a more suitable type instead of Int for referring to RowIndex and ColumnIndex. At least it makes the errors detectable at runtime by throwing exceptions. Int and Word types do not.

ghci> :i RowIndex
type RowIndex :: *
newtype RowIndex = RowIndex {unRowIndex :: GHC.Num.Natural.Natural}
        -- Defined at src/Codec/Xlsx/Types/Common.hs:89:1

ghci> RowIndex (-1)

<interactive>:14:12: warning: [GHC-97441] [-Woverflowed-literals]
    Literal -1 is negative but GHC.Num.Natural.Natural only supports positive numbers
RowIndex {unRowIndex = *** Exception: arithmetic underflow

One other approach can be using smart constructors and keeping the two types opaque. Something like:

mkRowIndex :: Int -> Maybe RowIndex
mkRowIndex n
  | n >= 0    = Just (RowIndex n)
  | otherwise = Nothing

But then the caveat is that we have to deal with Maybes everywhere we end up referring RowIndex or ColumnIndex.

Also, I'm not sure that Int is an intentional but just wanted to bring this up.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions