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.
You probably want a data type that can represent either an int or a float.
Where
datais:Now your
funcargument can be a function with typenum -> numbut notnum -> 'aas you want a list ofnumas 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.