From: Robert Klemme Date: 2005-12-29T20:07:54+09:00 Subject: Re: [ANN] (Real) Primitive Ruby Generics support Isaac Devine wrote: > On Wed, 28 Dec 2005 23:24:01 +0900 > Florian Gro� wrote: >>> I have been hacking away to create a simple library that adds >>> generics-like qualities to ruby. At the moment you can define >>> methods with type-matches, defaults if no match and different >>> number of argument matches. >> >> Been there, done that: >> >> http://ruby-contract.rubyforge.org/ >> >> New ideas are very welcome. >> > > Thanks! I've quickly looked at the ruby-doc for that. It's seems to > only be able to specific "contracts" for classes, with method > signatures as a subset. What my goal for generics is to be able to > choose what code to execute based on method/class parameter types. > ie. > converting : > def foo(arg) > if arg.kind_of? String > puts "it is a string! reverse it! #{arg.reverse}" > elsif arg.kind_of? Fixnum > puts "Fixnum! double it! #{2*arg}" > end > end > > into: > > generic_method :foo, String do |arg| > puts "it is a string! reverse it! #{arg.reverse}" > end > > generic_method :foo, Fixnum do |arg| > puts "Fixnum! double it! #{2*arg}" > end That's not generics but overloading. I'm sorry, but with these things it's really important to use teminology properly otherwise you'll likely cause a lot of misunderstandings. > In the future I would like to be able to extend this to classes as > well. One implication of this we will be the ability to get rid of > "adapter" classes when joining heirachys. One example would be adding > support to reading from a String when a class can only read from a > File. > > ie. > generic_class :SomeClass, String do > def getline > .. > end IMHO this is a bad example because you can turn a String into a StringIO which supports IO like behavior. If some method works on an IO instance it almost always works on a StringIO, too. > Another wish is for pattern matching: > generic_method :foo, :a, :b :a do ... > where wherever :a occurs it must be the same type so: > foo 4 "a" 4 passes > but > foo "a" 4 4 fails. Sounds like you wanted to reimplement some features very common with functional languages in Ruby. Why do you do that? > P.S. I have an updated version which generates methods instead of > lookup + some extras. Nobody mind if I post it to the ml later(ie no > negative)? If you really intend to go further down that road I suggest you create a project on rubyforge (or merge with an existing project). I'm sorry to be so discouraging but this seems like yet another attempt to retrofit other languages' features to Ruby instead of using it the way it is. Kind regards robert