Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you "partially" derive a Typeclass?

In the following toy example we create a new type D for which we want to implement the typeclass Show. Now let's say for all constructors the derived show function would be just fine, except for one special case A for which we want to override that default.

Is it possible to do that, or can you just have all or none of them derived?

data D = A | B | C
  deriving (Show)

-- goal: 
-- show A = "A is special"
-- show B = "B"
-- show C = "C"

main = print $ show A

Try it online!

like image 742
flawr Avatar asked Apr 25 '21 16:04

flawr


People also ask

Is the class of partially decidable languages closed under complement?

@YuvalFilmus I would say the class of partially decidable language is not closed under complement, due to the halting problem when trying to construct a decider for such a language... Now try to answer your question using this information.

What does it mean to partially derive a function?

Computationally, when we have to partially derive a function f ( x 1, …, x n) with respect to x i, we say that we derive it “as if the rest of the variables were constants”. This derivative is then denoted by:

How do I generate a partial derivative in latex?

The partial derivative symbol is generated in LaTeX with the command \partial, so that the previous equation was produced with the code: If you have to deal with several partial derivatives along with your document, it is not practical to have to write every time fraction with the corresponding \partial symbols.

How to deal with multiple partial derivatives of a function?

If you have to deal with several partial derivatives along with your document, it is not practical to have to write every time fraction with the corresponding \partial symbols. It would be better to define a command that you passe only the function and the variable with respect to which we want to derive.


1 Answers

This can be done using generics. generic-data provides a default implementation of showsPrec, gshowsPrec, and you can use pattern-matching to handle non-default cases before it:

{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
import Generic.Data (gshowsPrec)

data D = A | B | C
  deriving (Generic)

instance Show D where
  showsPrec _ A = ("A is special" ++)
  showsPrec n x = gshowsPrec n x
like image 127
Li-yao Xia Avatar answered Oct 19 '22 05:10

Li-yao Xia