It is impossible to do this directly, for a very simple reason - the choice of an instance only looks at the "head", i.e. to the part after =>
. Nothing is placed in the context - the part before =>
- can affect the selected instance.
For simple cases, you can often avoid the problem, for example, if there are a limited number of types of “base case”. A common example is lists of type types where you will have a recursive case for Cons
and a base case of Nil
and what it is.
In the general case, you usually need some type of conditional test type, which selects a type based on the fulfillment of some condition, and then passes the actual implementation to the helper class, which takes the conditional value of the result as a parameter and uses it to instance selection.
source share