[Haskell-cafe] Views

Stephan Friedrichs deduktionstheorem at web.de
Sat Sep 13 14:19:46 EDT 2008


List-like data structures should IMHO provide safe versions of 'head'
and 'tail' (with safe I mean 'not partial', i. e. functions that don't
provoke an 'error' when called with an empty collection). As far as I
know, this is usually called 'view' and and has a type signature like

view :: SomeDataStructure a -> View a


data View
  = Empty
  | Cons a (SomeDataStructure a)

A good example for this is Data.Sequence. My question is: Why is this
not expressed in terms of Maybe?

view :: SomeDataStructure a -> Maybe (a, SomeDataStructure a)

This would be easier to use, as there's no need for a new View type and
because Maybe already provides instance declarations for a lot of useful
classes (Functor, Monad, etc.) and handy helper functions (e. g.
'maybe'). Then you could, for instance, say:

head xs = maybe undefined fst (view xs)
tail xs = maybe undefined snd (view xs)

You can of course argue that you want viewl and viewr to have different
types in the case of Data.Sequence, but this is not the case for other,
rather one-ended, data types, is it?

Long story short, my problem is the following: I want to provide a
'view' function for Data.Heap in my heap [1] package and I don't know

a) ... to use Maybe
b) ... to provide my own Data.Heap.View type
c) ... a Data.View package with a View type should be included in
   the containers- or even base-package. This would prevent lots of
   small projects from creating totally equivalent View types.

Maybe there even exists a Data.View package that I didn't find?


[1] http://hackage.haskell.org/cgi-bin/hackage-scripts/package/heap-0.3.1


Früher hieß es ja: Ich denke, also bin ich.
Heute weiß man: Es geht auch so.

 - Dieter Nuhr

More information about the Haskell-Cafe mailing list