简体   繁体   English

haskell:自定义数据类型中的计算字段

[英]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 然后myGrid = Grid 5 6

or does this have to be or can only be done with Class ? 或者这必须是或只能用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. 如果由于某种原因,您想要预先计算c并将其存储在值中,请定义一个智能构造函数。

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. Haskell中的数据和函数分离比OO语言更严格。 data only defines a new type, not the operations on that type. data仅定义新类型,而不是该类型的操作。 Record syntax only provides projections of the form Grid -> x for some type x ; 记录语法仅为某些类型x提供表格Grid -> x投影; it doesn't let you define anything more complicated. 它不会让你定义任何更复杂的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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