logo       

Re: assorted beginner questions: msg#00520

lang.scala

Subject: Re: assorted beginner questions

> is there any way to automatically inherit certain behaviors, a la
> 'derives' in haskell? any tools/approaches using metaprogramming,
> reflection, or something else? in particular, i'd like to
> (de)serialize my objects, a la python's pickle or haskell's read/show,
> without writing any serialization code (or at most once).

There are some frameworks for this in development. Philip Haller has a
library of pickling combinators in style of what Andrew Kennedy did for
Haskell.


does anybody have more info about this? do the combinators use scala.reflect?

No, the combinators do not use `scala.reflect'. The original use case is to use it on JVMs that do not support reflection (such as the KVM/CLDC).

In fact, with sufficient reflection support a single, general serialization routine could be written that handles all possible cases (it should still be extensible to allow to exclude certain parts from serialization such as caches etc.).

There are combinators for
- bytes (`byte')
- ints (`nat')
- booleans (`bool')
- strings (`string')
- byte arrays (`bytearray')
- pairs, triples (`pair', `triple')
- lists (`list')
- class hierarchies (`data')

Short example:
Suppose, we want to pickle values of the following case class:

case class Person(name: String, age: int)

First, we construct a suitable pickler using the combinators from `scala.io.BytePickle':

val personPickler =
wrap((data: {String, int}) => Person(data._1, data._2),
(pers: Person) => {pers.name, pers.age},
pair(string, nat))

The pickler `pair(string, nat)' can pickle values of type {String, int}. We use the `wrap' combinator to construct a pickler for values of type `Person' by pre- and post-processing a pair.

To compress pickled data the `share' meta-combinator can be used that takes an arbitrary pickler and enables structure sharing for it.

val sharingPersonPickler = share(personPickler)

There is an example on the Scala wiki that uses the `data' combinator to pickle a class hierarchy of lambda terms:
http://scala.sygneca.com/libs/io

Hope this helps,
Philipp




<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise