haskell - 数据构造函数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
不工作
先感谢您
解决方案
使用模式匹配
我们可以构造一个使用模式匹配的函数:
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}
推荐阅读
- ios - TableView didselectrow 没有推送另一个视图
- c# - 绑定:使用 MVVM 在 Xamarin.forms 中找不到属性
- python - 如何在python中对计数器的计数器求和?
- angular - 刷新页面时如何在 Angular 上重新加载同一页面?
- python - numpy.any() 用于条件检查的问题
- cypress - 如何在 Cypress 中读取动态文件
- python - 我的项目在计算器中的对齐有问题
- azure-devops-extensions - 如何对 Azure DevOps Server 中的扩展进行故障排除?
- python - Pandas 数据框中的多个条目
- python - 如何切片抓取的 xml 数据并在 python 中创建列表