[Haskell-beginners] Can i define a record without defining access method.
yi huang
yi.codeplayer at gmail.com
Sat Jul 9 17:59:51 CEST 2011
On Sat, Jul 9, 2011 at 6:45 PM, Tom Murphy <amindfv at gmail.com> wrote:
> On 7/9/11, yi huang <yi.codeplayer at gmail.com> wrote:
> > I'm trying to create a haskell implementation of json rpc, I try to
> define
> > protocol using record like this:
> >
> > data Request = Request {
> > version :: Integer
> > , id :: Integer
> > , method :: String
> > , args :: [Value]
> > } deriving (Typeable, Data, Show)
> >
> > data Response = Response {
> > version :: Integer
> > , id :: Integer
> > , code :: Integer
> > , method :: String
> > , result :: Value
> > } deriving (Typeable, Data, Show)
> >
> > so i can use json library to encode/decode it.
> > But this code fails, because haskell will define access function
> > automaticlly, and function names conflicts.
> > My question is, is there a way i can define record without access
> function,
> > so i can have same attribute name in multiple record.
>
>
> If you don't want access functions defined, you can simply not name
>
>> your record fields:
>
>>
> data Request = Request Integer Integer String [Value]
>
>> deriving (Typeable, Data, Show)
>
>>
>
> If you want it to be more readable, you can define type synonyms:
>
>>
> type ID = Integer
>
>> type Version = Integer
>
>> [...]
>
>>
> data Request = Request Version ID Method Args
>
>> deriving (Typeable, Data, Show)
>
>>
> The two "instances" of ID won't conflict, then.
>
I have to define it as a record, so aeson can inspect the attribute names
and encode it to a json object automatically, for example:
"{\"args\":[],\"id\":1,\"method\":\"test\",\"version\":1}"
But normal data constructor would be encoded to an array.
Though i can define it as a normal data constructor, and implement ToJSON
class manually, but the code would be more verbose.
>
>
> Tom
>
--
http://www.yi-programmer.com/blog/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110709/5dfd183f/attachment.htm>
More information about the Beginners
mailing list