How do I know if a type is an instance of a class in Haskell?

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 ( / / , / , ).

+4
2

, . , - :

class GenericBinaryTree t where
    is_leaf :: t a -> Bool
    left :: t a -> t a
    node :: t a -> a
    right :: t a -> t a

prettyprint_helper :: (GenericBinaryTree f, Show a) => f a -> [String]

, , , . , node, Show constrain prettyprint_helper singnature. GenericBinaryTree :

instance GenericBinaryTree Tree 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
+4

node :: a -> b, a GenericBinaryTree, b - -. - , , show.

node :: Show b => a -> b , b show , : , , b !

, class. ,

instance Alternative f where
  empty :: f a

, f, ... f a a.

MultiParamTypeClasses

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}

class GenericBinaryTree b a | a -> b where
  is_leaf :: a -> Bool
  left :: a -> a
  node :: a -> b
  right :: a -> a

showNode :: (Show b, GenericBinaryTree b a) => a -> String
showNode = show . node

.

+2

All Articles