为什么我不能使用存在量化类型的记录选择器? [英] Why can't I use record selectors with an existentially quantified type?
问题描述
使用存在类型时,我们必须使用模式匹配语法来提取 forall
ed值。我们不能使用普通的记录选择器作为函数。 GHC会报告一个错误,并建议使用与 yall
定义的模式匹配:
When using Existential types, we have to use a pattern-matching syntax for extracting the forall
ed value. We can't use the ordinary record selectors as functions. GHC reports an error and suggest using pattern-matching with this definition of yALL
:
{-# LANGUAGE ExistentialQuantification #-}
data ALL = forall a. Show a => ALL { theA :: a }
-- data ok
xALL :: ALL -> String
xALL (ALL a) = show a
-- pattern matching ok
-- ABOVE: heaven
-- BELOW: hell
yALL :: ALL -> String
yALL all = show $ theA all
-- record selector failed
forall.hs:11:19:
Cannot use record selector `theA' as a function due to escaped type variables
Probable fix: use pattern-matching syntax instead
In the second argument of `($)', namely `theA all'
In the expression: show $ theA all
In an equation for `yALL': yALL all = show $ theA all
我的一些数据超过5个元素。如果我
使用模式匹配,很难维护代码:
Some of my data take more than 5 elements. It's hard to maintain the code if I use pattern-matching:
func1 (BigData _ _ _ _ elemx _ _) = func2 elemx
是否有一种很好的方法可以使代码保持可维护状态或将其包装以便我可以使用某种选择器?
Is there a good method to make code like that maintainable or to wrap it up so that I can use some kind of selectors?
推荐答案
您可以在模式匹配中使用记录语法,
You can use record syntax in pattern matching,
func1 BigData{ someField = elemx } = func2 elemx
可以工作,而且对于庞大的类型来说打字少得多。
works and is much less typing for huge types.
这篇关于为什么我不能使用存在量化类型的记录选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!