Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [O'Caml]Making program generic/polymorphic?
Index -> Programming, General Programming -> Functional Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
richcash




PostPosted: Wed Oct 24, 2007 11:03 pm   Post subject: [O'Caml]Making program generic/polymorphic?

Ocaml:
class foo init_value =
        object
              val array = Array.create 5 init_value
              method get i = array.(i)
        end;;


The above won't work in O'Caml because the compiler doesn't know what the type of init_value is, so it doesn't know what type get will return. I can't figure out how to get around this, I'm not that good in polymorphic types.

This was my first guess, but it doesn't work either.
Ocaml:
class foo (init_val : 'a) =
        object
              val array = Array.create 5 init_val
              method at : (int -> 'a). i = array.(0)
        end;;


Can someone help me to get around this problem? Is making a polymorphic method even necessary? I know it's simple but it's something I never learned. Thanks.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Thu Oct 25, 2007 9:52 am   Post subject: RE:[O\'Caml]Making program generic/polymorphic?

Yes, it is necessary, as O'Caml has no way of inferring the type of init_val statically.

code:
# class ['a] foo (init_val : 'a) =
    object
      val array = Array.create 5 init_val
      method at i = array.(i)
    end;;
class ['a] foo : 'a -> object val array : 'a array method at : int -> 'a end
richcash




PostPosted: Thu Oct 25, 2007 1:10 pm   Post subject: Re: [O'Caml]Making program generic/polymorphic?

Excellent! Thank you.
Display posts from previous:   
   Index -> Programming, General Programming -> Functional Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: