Search code examples
haskellrecordexistential-type

Why can't I use record selectors with an existentially quantified type?


When using Existential types, we have to use a pattern-matching syntax for extracting the foralled 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

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?


Solution

  • You can use record syntax in pattern matching,

    func1 BigData{ someField = elemx } = func2 elemx
    

    works and is much less typing for huge types.