Search code examples
typesocaml

OCaml functions on uncertain data types


I have a data type,

type data = IntData of int list | FloatData of float list

I want to write a function with signature map : data -> ('a -> 'a) -> data which will apply the given function to each element in the data's list.

The compiler doesn't like the following code, for understandable reasons.

let rec map dat func =
  match dat with 
  | IntData il = IntData (List.map func il)
  | FloatData fl = FloatData (List.map func fl)

Of course, the compiler can't make sense of the idea that func could have a different type in each of these cases.

On the other hand, I can't think of how to accomplish this kind of behavior, except to write a separate map function, one for IntData and another for FloatData. But that seems like the kind of wasteful duplication of code that OCaml strives to avoid.


Solution

  • You probably want a data type that can represent either an int or a float.

    type num = Int of i | Float of i
    

    Where data is:

    type data = num list
    

    Now your func argument can be a function with type num -> num but not num -> 'a as you want a list of num as the outcome.

    Of course, this means you cannot be assured your lists are only of ints or only floats. It would be important to specify why you want to do this as there may be a better solution to the larger problem.