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

From: Vincent St-Amour (stamourv at ccs.neu.edu)
Date: Sun Mar 4 19:17:58 EST 2012

You may want to have a look at unstable/generics:
http://docs.racket-lang.org/unstable/Generics.html?q=unstable/generics

It's currently unstable, but I'm working on moving it to a more
permanent place in the near future, hopefully by the next release.

Vincent


At Sun, 4 Mar 2012 14:15:55 -0800,
Helmut Rohrbacher wrote:
> 
> [1  <multipart/alternative (7bit)>]
> [1.1  <text/plain; ISO-8859-1 (7bit)>]
> 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
> [1.2  <text/html; ISO-8859-1 (quoted-printable)>]
> 
> [2  <text/plain; us-ascii (7bit)>]
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users

Posted on the users mailing list.