简体   繁体   中英

algebraic data type field name not recognised

I have a declaration of an algebraic data type in one module and use this data structure in another.

In Convert.hs I have

module Convert (makeTables, Table) where

data Table = Table {
    headers :: [[String]],
    datarows :: [[String]]
    }
    deriving (Show)  
-- ...

In another module I have:

import Convert

titles :: Table -> [String]
titles t = map (intercalate " ") (headers t)

The compiler apparently is aware of Table as it does pass the function signature. However, headers field name is not available:

    Variable not in scope: headers :: Table -> [[[Char]]]
   |
10 | titles t = map (intercalate " ") (headers t)
   |                                   ^^^^^^^

Any remedies possible to this? Many thanks in advance.

You need to export the fields of the data type:

module Convert (makeTables, Table(..)) where
--                               ~~~~

Currently you only export the data type itself, so it's opaque—the fields are private to the Convert module. This is useful if you want a data structure that can only be constructed or manipulated using a certain public API. (Eg the “smart constructor” pattern.)

Typically if you plan to import Convert unqualified, you would prefix the field names so they don't clash with anything:

data Table = Table
  { tableHeaders :: [[String]]
  , tableDataRows :: [[String]]
  } deriving (Show)

But you can also leave them as-is and import the module qualified, eg:

import Convert (Table)
import qualified Convert

titles :: Table -> [String]
titles t = map (intercalate " ") (Convert.headers t)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM