[Haskell-cafe] basic field questions

Brian Hulley brianh at metamilk.com
Wed Jan 24 06:49:19 EST 2007


jamin1001 wrote:
> Hi, I am new at Haskell and have some basic questions.
> So then how should this be done?  What if I want to do something like
>
> data Chair = Chair {pos:: Int, color :: Int}
> data Table = Table {pos:: Int, color :: Int}

Unfortunately you have to think up different names for all constructors and 
field names that are declared anywhere in the same module. A possible 
methodical way to do this is to prefix all names by the type name (with 
first letter lowercase of course) eg:

    data Chair = Chair {chair_pos:: Int, chair_color :: Int}
    data Table = Table {table_pos:: Int, table_color :: Int}

The reason is that when you declare a fieldname this also introduces a top 
level function with the same name which returns the relevant component of 
the record ie in the above the following top level functions are generated 
by the compiler:

    chair_pos :: Char -> Int
    chair_color :: Chair -> Int
    table_pos :: Table -> Int
    table_color :: Table -> Int

>
>
> Also, could someone tell me why this doesn't compile in GHC:
>
> data Test = A {a::Int} | B {a::Int, b::Int}
> data Test2 = C {c::A}
>
> (Test2 line): Not in scope: type constructor or class 'A'

(A) is a data constructor whereas you need a type here, so it should be:

    data Test2 = C {c :: Test}

Brian.
-- 
http://www.metamilk.com 



More information about the Haskell-Cafe mailing list