Short form (this will solve my problem at least)
How can I do something like this:
try_to_show :: a -> String
try_to_show val = if (val is instance of Show) (show val) else "Cannot show"
I probably do this completely wrong (unhaskell path); I am just studying, so please let me know if there is a better way to approach this.
Context: I write a bunch of tree structures. I want to reuse my function prettyprintfor binary trees. However, not all trees can use the common data type Node/ Branch; different trees need different additional data. Therefore, to reuse the function prettyprintthat I was thinking about creating the class, different trees would be instances:
class GenericBinaryTree a where
is_leaf :: a -> Bool
left :: a -> a
node :: a -> b
right :: a -> a
, , node, printprint .
:
prettyprint_helper :: GenericBinaryTree a => a -> [String]
prettyprint_helper tree
| is_leaf tree = []
| otherwise = ("{" ++ (show (node tree)) ++ "}") : (prettyprint_subtree (left tree) (right tree))
where
prettyprint_subtree left right =
((pad "+- " "| ") (prettyprint_helper right)) ++ ((pad "`- " " ") (prettyprint_helper left))
pad first rest = zipWith (++) (first : repeat rest)
Ambiguous type variable 'a0' in the constraint: (Show a0) arising from a use of 'show' (show (node tree))
( , prettyprint)
data Tree a
= Branch (Tree a) a (Tree a)
| Leaf
instance GenericBinaryTree (Tree a) where
is_leaf Leaf = True
is_leaf _ = False
left (Branch left node right) = left
right (Branch left node right) = right
node (Branch left node right) = node
node :: a -> [String] / , . prettyprint , , .
, , node Show ? ? - , - -, .
-
prettyprint :: Show a => a -> String
, , ( Node), . Node Show b => a -> b ( / / , / , ).