Getting the number of fields in a Haskell record

I present a table for storing data as a Haskell record, and I was wondering if there is a function to get the number of fields set for the record?

I ask how I have a type class to represent a table, and one of the functions of the class is noOfCols; which correspond to the number of fields in the record representing the table.

data Price = Price {bid=[Float], ask=[Float]}

class Table a where
   noOfCols :: a -> Int
   ...

instance Table Price where
   noOfCols t = 2
   ...

Therefore, the problem is that I will constantly add new fields so that I can forget to update the implementation of the noOfCols instance when I add new columns (fields) to Price; that is, leave it at 2 when I now have 3 or more fields.

Is there a function that can provide the number of fields for a given record, so I do not need to do manual editing every time I change the record?

+4
2

, . :

{-# LANGUAGE DeriveDataTypeable #-}

import Data.Data

data Price = Price {bid :: [Float], ask :: [Float]}
  deriving (Typeable, Data)

noOfCols :: Data a => a -> Int
noOfCols = gmapQl (+) 0 (const 1)

:

GHCi> noOfCols (Price [1,2] [3,4,5])
2
GHCi> noOfCols (0,0,0,0)
4
+4

noOfCols - - Price, ..

noOfCols = arity Price

. Haskell: ? arity (. ). (: @kosmikus - - ).

: , [[Float]] - , ..

type Price = [[Float]]

bid :: Price -> [Float]    
bid = (!! 0)

ask :: Price -> [Float]
ask = (!! 1)

noOfCols :: Price -> Int
noOfCols = length
+2

Source: https://habr.com/ru/post/1536225/


All Articles