I am using the hardware description tool Clash. Though this is a hardware description tool, my question is purely about Haskell.
There is a datatype of the form
data Signal dom a = ...
This datatype has an Applicative instance as follows:
instance Applicative (Signal domain) where
pure = signal#
(<*>) = appSignal#
I have defined some functions which can sensibly take either Signal dom (Foo a b) or Foo a b. That is, they can either take a value wrapped in an Applicative, or they can take the value and then call pure to wrap it themselves.
I see two (ugly) ways to implement such a function:
Create two versions of the function, one taking the "naked" value and the other taking the Applicative. Inside the first function, I call
purethen delegate to the second function. These functions look something like the following:f :: (Foo a b) -> Signal dom Baz -> Signal dom Bar f = f' . pure f' :: Signal dom (Foo a b) -> Signal dom Baz -> Signal dom Bar f' = ...Create only one version of the function, then expect the user to call
pureas needed.
I would like to create a typeclass to solve this, wherein the instance for Foo a b is pure and the instance for Signal dom (Foo a b) is id. But I cannot see any way to define such a thing.
Is there a way to define a typeclass, or is there another solution I have overlooked?
Of course if they can take an applicative then they can take a pure value. That's why we have
pure. It may not be the most "fluent" thing but puttingpureat the call site does have its advantages -- namely that the reader of the code knows that this value doesn't vary, and also that it is permitted to.In any case, if the argument types are some fixed data type like
Foothen you could:Whether that's worth it is up to you.
And if you want it to work on polymorphic types like
There is, as far as I know, no good solution. There are things involving overlapping instances that may appear to work for the simplest examples, but they break very easily.