
-----------------------------------
richcash
Wed Oct 24, 2007 11:03 pm

[O'Caml]Making program generic/polymorphic?
-----------------------------------
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.
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.

-----------------------------------
wtd
Thu Oct 25, 2007 9:52 am

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.

# 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
Thu Oct 25, 2007 1:10 pm

Re: [O'Caml]Making program generic/polymorphic?
-----------------------------------
Excellent! Thank you.
