首页 > 解决方案 > 数据构造函数haskell中的访问类型字段

问题描述

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

data Object = Object Type1 Type2 Type3 Type4
  deriving(Eq,Show)
type Type1 = Float
type Type2 = Bool
type Type3 = Int
type Type4 = String

我定义了一个名为

construct = Object 5.6 True 10 "World"

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

Type4 construct 

不工作

先感谢您

标签: haskelltypessyntaxoutput

解决方案


使用模式匹配

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

objectType1 :: Object -> Type1
objectType1 (Object x _ _ _) = x

使用记录语法

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

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

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

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

setObjectType1 :: Type1 -> Object -> Object
setObjectType1 t o = o { objectType1 = t}

推荐阅读