I am a F# newbie.
I have 2 classes, Base and Derived.
Base has a number of methods. Derived inherits some methods as they are and some it overrides. Derived class also introduced new methods.
I have a set of objects, some are Base and some are Derived.
There is a list of 2 elements tuples, second element of the tuple being a method of a polymorphic hierarchy.
Let’s consider my program that reads input and for each input goes through the list applying the first element of each tuple (a predicate) to the input.
If the predicate is true, then it invokes the second element of the tuple on an object that could be Base or Derived (depending, again, on the value of the first element of the tuple).
It’d be nice to a single list of such tuples, instead of 2 lists as it is now(one for Base and one for Derived). Is this possible?
Assume Base class defines method1 and method2.
Assume Derived class defines (overriding) method2 and method4.
let predList =
[(predicate1, Base.method1);
(predicate2, method2);
(predicate4; Derived.method4)
...
]
while ... do
let input = ReadInput
if IsBase(input)
then
let method = List.Find matchingPredicate predList
let baseObj = ChooseBaseObject(input)
baseObj.method // ????
else
let method = List.Find matchingPredicate predList
let derivedObj = ChooseDerivedObject(input)
derivedObj.method // ????
With such code, a given input that satisfies predicate2 may trigger a call to Derived.method2 or Base.method2 depending on what IsBase(input) returns.
The simplest thing is maybe wrapping your
method‘s into a group of standalone functions: