Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I partially derive Show?

Tags:

haskell

I have written this code to pretty-print a tree:

data Node = A | B | C | Tree Node [Node]
    deriving (Show, Eq)

printTree' :: Int -> Node -> [String]
printTree' spaceCount (Tree node children) = (printTree' spaceCount node)
    ++ concat (map (\child -> printTree' (spaceCount+2) child) children)
printTree' spaceCount leaf = [(replicate spaceCount ' ') ++ (show leaf)]

printTree :: Node -> String
printTree node = unlines (printTree' 0 node)

Example output:

*Main> putStr $ printTree $ Tree A [Tree A [A,B,C], C]
A
  A
    A
    B
    C
  C

Now I would like to make this the implementation for show. This approach is close but I can't find a way to call the built-in show:

instance Show Node where
    show (Tree node children) = printTree (Tree node children)
    show _ = "node... can I call the built-in show here?"

(In this example, I could just deal with A, B, and C. But in the real code, there are many node types.)

like image 451
default.kramer Avatar asked Jul 06 '15 15:07

default.kramer


People also ask

What does a partial derivative show?

Partial derivatives tell you how a multivariable function changes as you tweak just one of the variables in its input.

How do you do partial derivation?

Partial Derivative Symbol Example: Suppose f is a function in x and y then it will be expressed by f(x, y). So, the partial derivative of f with respect to x will be ∂f/∂x keeping y as constant. It should be noted that it is ∂x, not dx.

What is ∂ called?

The symbol ∂ indicates a partial derivative, and is used when differentiating a function of two or more variables, u = u(x,t). For example means differentiate u(x,t) with respect to t, treating x as a constant.


2 Answers

The only way I can see to do this is to separate into two types.

data Tree node = Tree node [Tree node]
data Node = A | B | C deriving Show

instance Show node => Show (Tree node) where ....
like image 163
MathematicalOrchid Avatar answered Oct 08 '22 14:10

MathematicalOrchid


Following MathematicalOrchid's reponse, the best way to do this is with a new type, but here's a better way to organize the types:

data Node = Leaf Leaf | Tree Node [Node] deriving Eq
data Leaf = A | B | C deriving (Eq, Show)

instance Show Node where
  show (Tree node children) = printTree (Tree node children)
  show (Leaf l) = show l
like image 30
Adam R. Nelson Avatar answered Oct 08 '22 15:10

Adam R. Nelson