Function overloading for minimze repetitive pattern

Viewed 76

To learn haskell I've been building an framework much like Python Pandas.

In this scenario, I've defined a data called Series

    data Series
  = SInt [Int] ByteString
  | SFloat [Float] ByteString
  | SByteString [ByteString] ByteString
  deriving (Show, Eq)

But due Haskell type system and my knowledge, I program simple functions like a Scalar Sum with this very repetitive coding pattern

sScalarSum :: Series -> Either Int Float
sScalarSum (SInt i _) = Left $ Data.List.sum i
sScalarSum (SFloat i _) = Right $ Data.List.sum i
sScalarSum (SByteString _ _) =
  error "Cannot sum strings. use applyDType to convert series to float or int"

Is there any form of overloading to minimize this code?

Can't I just do something like this?

sScalarSum :: Series -> Either Int Float
sScalarSum (Series i _) = Left $ Data.List.sum i
1 Answers

You don't need to encode this information at the constructor level. Define a Series to be a parameterized list of anything

data Series a = Series [a] ByteString

but limit sScalarSum to summable types.

sScalarSum :: Num a => Series a -> a
sScalarSum (Series values _) = Data.List.sum values

More generally, you can define a Foldable instance for Series and use sum directly on your value.

instance Foldable Series where
    foldMap f (Series values _) = foldMap f values

sScalarSum :: Num a => Series a -> a
sScalarSum = Data.List.sum
Related