Language extension idea (was Re: [Haskell-cafe] Re: OCaml list sees...)

Tom Pledger wrote:
Something along these lines:
class List l a | l -> a where nil :: l cons :: a -> l -> l
But that's not of much use, because there isn't a class method to recover the elements of a List. We could add more methods (corresponding to null, head, and tail)
Actually we merely need to add a deconstructor. Also, we can leave the type of elements fully polymorphic. Something like this:
class List l where nil :: l a cons :: a -> l a -> l a decon :: l a -> w -- on empty -> (a -> l a -> w) -> w
instance List [] where nil = [] cons = (:) decon [] on_nil on_cons = on_nil decon (h:t) on_nil on_cons = on_cons h t
we can then write truly generic list-processing functions:
rev:: List l => l a -> l a rev l = rev' l nil where rev' l acc = decon l acc (\h t -> rev' t (cons h acc))
not in a terribly convenient way though. *Foo> rev "abc" "cba"

oleg@pobox.com wrote: [...]
Actually we merely need to add a deconstructor. Also, we can leave the type of elements fully polymorphic. Something like this:
class List l where nil :: l a cons :: a -> l a -> l a decon :: l a -> w -- on empty -> (a -> l a -> w) -> w
instance List [] where nil = [] cons = (:) decon [] on_nil on_cons = on_nil decon (h:t) on_nil on_cons = on_cons h t
Yes. That 'decon' function corresponds to the 'case' function I went on to suggest later in my post, as part of a data-constructors-as-class-members language extension. I used 'class List l a | l -> a', not 'class List l', so that there could be an instance for PackedString.
we can then write truly generic list-processing functions:
rev:: List l => l a -> l a rev l = rev' l nil where rev' l acc = decon l acc (\h t -> rev' t (cons h acc))
not in a terribly convenient way though.
*Foo> rev "abc" "cba"
It could get more convenient, though, if we have data-constructors-as-class-members and move the familiar list constructors into the List class. (The following might need to be built into the compiler, because of the special [] syntax.) class List l a | l -> a where [] :: l (:) :: a -> l -> l data OrthodoxLinkedList a = NilOLL | ConsOLL a (OrthodoxLinkedList a) instance List (OrthodoxLinkedList a) a where ... Then existing definitions of list functions would work at the more generic level. Regards, Tom
participants (2)
-
oleg@pobox.com
-
Tom Pledger