Haskell Type Constraint

I am trying to define a couple instances of a class inductively. I.e:

class Foo ab | a -> b where foo :: a -> b instance (not?)Foo a => Bar ab foo x = ... instance Foo a => Bar ab foo x = ... 

The first instances define the underlying action, and the seconds recursively call foo. Is there any way to do this? A good example would be to smooth the list, where in the first case it is an identification function and in the second a recursive concat application.

+6
source share
2 answers

Here is an implementation of the flatten function that works with any level of a nested list. I would not recommend using it, although here is just to demonstrate how to achieve something like this in haskell.

+5
source

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.

+8
source

Source: https://habr.com/ru/post/909908/


All Articles