数据构造函数haskell中的访问类型字段

Has*_*ase 3 syntax haskell types output

我有一个问题,如何访问数据构造函数中的某些类型。假设我得到了这个代码示例

data Object = Object Type1 Type2 Type3 Type4
  deriving(Eq,Show)
type Type1 = Float
type Type2 = Bool
type Type3 = Int
type Type4 = String
Run Code Online (Sandbox Code Playgroud)

我定义了一个名为的函数

construct = Object 5.6 True 10 "World"
Run Code Online (Sandbox Code Playgroud)

我如何从构造打印某些类型,例如我想从构造打印“世界”我如何获取该信息。

Type4 construct 
Run Code Online (Sandbox Code Playgroud)

不起作用

先感谢您

Wil*_*sem 6

模式匹配

我们可以构造一个使用模式匹配的函数:

objectType1 :: Object -> Type1
objectType1 (Object x _ _ _) = x
Run Code Online (Sandbox Code Playgroud)

记录语法

我们还可以使用记录语法定义数据类型:

data Object = Object {objectType1 :: Type1,
                      objectType2 :: Type2,
                      objectType3 :: Type3,
                      objectType4 :: Type4} deriving(Eq, Show)
Run Code Online (Sandbox Code Playgroud)

Haskell 然后会自动构造 getter,所以你隐式构造了这样的objectType1函数。

我们也可以使用这样的记录语法作为“ setter ”,例如:

setObjectType1 :: Type1 -> Object -> Object
setObjectType1 t o = o { objectType1 = t}
Run Code Online (Sandbox Code Playgroud)