[racket] Type-class-like idiom in Racket?

From: Helmut Rohrbacher (helmut.rohrbacher at gmail.com)
Date: Sun Mar 4 17:15:55 EST 2012

So I have code that looks similar to this toy example in a Common Lisp
project:


(defgeneric to-list (data)
  (:documentation "Convert given data type to a proper list"))

(defmethod to-list ((data list))
  list)

(defmethod to-list ((data vector))
  (coerce data 'list))

(defmethod to-list ((data binary-tree))
  (traverse #'(lambda (x) x) data 'in-order))

;;; ... So on for other collection datatypes ...


This way I can write a function to work on multiple collection types
without having to define multiple methods to specialize on each.  In
addition it allows me to define TO-LIST method for any future types I would
to use those functions on. From what I understand this would be done
similarly in Haskell with a type-class:

class Listable a where

toList :: a -> [b]

But I am not a Haskell expert, and my code doesn't literally have TO-LIST.

I see that Racket has generic functions, but they see to work a bit
differently that CLOS-style generics.  Further, like Haskell's type-classes
I would like to be able to provide a contract for functions that take a
Listable type:

(provide

(contract-out

<...>

[foo (-> listable? bar?)]

<...>))


I can do this in CL using a :BEFORE method

(defmethod foo :before ((collection t) <...>)

(unless (find-method #'to-list () (list (class-of collection)) nil) ;
ensure collection object has TO-LIST method

; otherwise raise error condition)

<...>)

What would be the appropriate Racket construct or idiom to get sort of
"type-class" or "interface" that can be enforced through contracts?

Thanks,
Helmut
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120304/2e79a6a6/attachment.html>

Posted on the users mailing list.