Hi,
Christoph Herrmann wrote
> Hi,
> I always find it annoying to have a lot of
> auxiliary functions for selecting elements of
> tuples. It would be nice to have, e.g.,
> an infix operator, say "#", that takes a tuple
> and an integer >constant< and delivers one element
> out of the tuple, e.g.:
> (a,b,c,d,e,f,g,h) # 0 = a
> (a,(b,c)) # 1 # 0 = b
It is possible to do something very similar to this in Haskell 1.3, using
the so called "Datatypes with Field Labels". This allows the user to attach
names to each field of a datatype definition, and assume that a field selection
function is provided at the top-level. For example, a data type for points
might be written as:
data Point = MkPoint {x :: Int, y :: Int},
allowing functions such as getX and getY to implemented by:
getX :: Point -> Int
getX p = x p
(getY defined dually).
One problem with this approach is that the selector functions x and y are
defined globally within the module. Thus, it is not possible to define further
datatypes using the selectors x and y.
> Of course, this operator will not have
> a Haskell type. Maybe something like a
> let-expression can be introduced by
> the compiler, if the type inference system
> has determined the length of the tuple.
> Do you think this will be possible?
An alternative solution to the problem is to extend Haskell with Standard ML
style records, which allow monomorphic operations over records to be defined,
thus introducing no new problems with type inference, and can be consider to
be a form of labelled tuples. We could now define the above example as
type Point = Rec {x::Int, y::Int}
getX :: Point -> Int
getX p = p.x.
As the type system can check statically for the presence of the field x, there
is no need to require that this field be unique to Points. A bonus of this
approach is that we might consider, as in Standard ML, product types of the
form (Type1,...,TypeN) to be short hand for record types
Rec {1::Type1,..., N::TypeN}, allowing just the notion of tuple selection
introduced by Christoph.
Alternatively we might just extend Haskell with a system of extensible
polymorphic records, where again tuples might be considered shorthand for
fixed sized records.
Many regards
Ben
--------
Benedict R. Gaster.
Functional Programming Group, Nottingham University.
Category theory: This is how our children will program!