Computer Science Canada

[O'Caml]Making program generic/polymorphic?

Author:  richcash [ 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.

Author:  wtd [ 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

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

Excellent! Thank you.


: