简体   繁体   中英

haskell : calculated fields in custom data types

Is it possible to do something that is equivalent to having a field in a data type that is automatically calculated from other fields in the data type. For example:

data Grid = Grid
  { x :: Int
  , y :: Int
  , c = (x * y) :: Int
  }

and then myGrid = Grid 5 6

or does this have to be or can only be done with Class ?

data Grid = Grid
  { x :: Int
  , y :: Int
  }

class Calculated a where
  c :: a -> Int

instance Calculated Grid where
  c g = x g * y g

Without any additional requirement, that's simply a function.

c :: Grid -> Int
c g = x g * y g

If, for some reason, you want to pre-compute c and store it in the value, define a smart constructor.

data Grid = Grid {x :: Int, y :: Int, c :: Int}

mkGrid :: Int -> Int -> Grid
mkGrid x y = Grid x y (x * y)

There is a stricter separation of data and functions in Haskell than in an OO language. data only defines a new type, not the operations on that type. Record syntax only provides projections of the form Grid -> x for some type x ; it doesn't let you define anything more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM