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.)
Partial derivatives tell you how a multivariable function changes as you tweak just one of the variables in its input.
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.
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.
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 ....
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With