Creating polymorphic recursive types in Haskell

I am trying to create a tree type in Haskell. I used this simple data constructor to store a tree, in which each node can be empty, be a sheet containing an integer, or be a node containing an integer with branches on two other sheets / nodes. Here is what I have:

module Tree ( Tree(Empty, Leaf, Node) ) where

data Tree = Empty
| Leaf Int
| Node Tree Int Tree
deriving(Eq, Ord, Show, Read)

This works fine, but I need to make the tree type polymorphic. I tried just replacing "Int" with "a", but it doesn't seem to work. Is there any other system for creating these types of polymorphic?

+5
source share
4 answers

, Tree, . ! ? , . !

-, , , Int, t. :

data TNode t a = Empty
               | Leaf a
               | Node (t a) a (t a)
               deriving (Eq, Ord, Show, Read)

TNode , ; . , , TNode :

newtype Tree a = Tree (TNode Tree a) deriving (Eq, Ord, Show, Read)

Tree , , , , :

Tree (Node (Tree Empty) 5 (Tree (Leaf 2)))

, , , ? , , .

, , - . , :

newtype NameTree a = NameTree (String, TNode NameTree a) deriving (Eq, Ord, Show, Read)

, :

toList f t = toList' f (f t) []
    where toList' f (Node t1 x t2) xs = toList' f (f t1) (x : toList' f (f t2) xs)
          toList' f (Leaf x) xs = x:xs
          toList' _ Empty xs = xs

TNode , :

treeToList = toList (\(Tree t) -> t)
nameTreeToList = toList (\(NameTree (_, t)) -> t)

, , , , , , Haskell (, ) .

+24
data Tree a = Empty
           | Leaf a
           | Node (Tree a) a (Tree a)
+16

Int a , Tree a ( ). data Tree a, , Tree , a. Node Tree Int Tree , Tree a, .

+4

.

, , .

, MyBool, :

data MyBool = False | True

*. , MyBool . - :

data MyMaybe a = Just a | Nothing

MyMaybe *->*, " " .

, , .

True MyBool , - . Just a -> MyMaybe a, a, MyMaybe a - , , ghci:

> let x = Just 5
> :t x
Maybe Int
> let y = Just
> :t y
a -> Maybe a

MyMaybe MyBool. , MyBool *, MyBool - . MyMaybe - , "" , .. * -> *. , MyMaybe, MyMaybe Int, MyMaybe Bool, MyMaybe [Int] ..

, * -> *, *->*->*, :

 data MyPair a b = Pair a b

MyPair , , MyPair Int Bool, MyPair Int Int ..

Accepting a home message is something like: since value constructors have type signatures, type constructors have good signatures, and this must be taken into account when planning a new data type.

http://en.wikipedia.org/wiki/Kind_%28type_theory%29

+2
source

All Articles