I have data type
data Constants = Constants { x1 :: Int, x2 :: Int, ... , x100 :: Int }
Names x1, x2, ..., x100 may have irregular naming.
Is there an elegant way to create Constants object from list of 100 Int values?
mkConstants :: [Int] -> Constants
mkConstants [x1, x2, ..., x100] = Constants x1 x2 ... x100 -- The bad way
What about reverse task?
extractInts :: Constants -> [Int]
extractInts (Constants x1 x2 ... x100) = [x1, x2, ..., x100] -- The bad way
Edit: see Reading long data structure in Haskell for a modified version when the record fields are of different types (i.e. not all ints).
One possibility would be to use type classes:
{-# LANGUAGE FlexibleInstances #-}
data Constants = Constants { a :: Int, b :: Int, c :: Int, d :: Int, e :: Int }
deriving Show
class Cons a where
cons :: a -> [Int] -> Maybe Constants
instance Cons Constants where
cons c [] = Just c
cons _ _ = Nothing
instance (Cons a) => Cons (Int -> a) where
cons f (x:xs) = cons (f x) xs
cons _ _ = Nothing
then, if the list is of the right size:
\> cons Constants [1..5]
Just (Constants {a = 1, b = 2, c = 3, d = 4, e = 5})
and otherwise you get nothing:
\> cons Constants [1..4]
Nothing
\> cons Constants [1..6]
Nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With