0

I have this type declaration, representing a binary tree:

data Bst a = Empty | Node (Bst a) a (Bst a)

As I'm new to Haskell, I can't figure how to use it. Could you show me how to initialize some of its instances?

3 Answers 3

3

Single Int node:

    2

 Node Empty (2::Int) Empty

The tree:

    2
   / \
  1   3

Node (Node Empty 1 Empty) 2 (Node Empty 3 Empty) :: Bst Int


    2
   / \
  1   3
       \
        5

Node (Node Empty 1 Empty) 2 (Node Empty 3 (Node Empty 5 Empty)) :: Bst Int
Sign up to request clarification or add additional context in comments.

3 Comments

Last example is incorrect, it should Node (Node (Node Empty 3 Empty) 2 Empty) 1 (Node Empty 3 Empty)
I think I was fixing as you were commenting.
Also (not that it's really important for the illustration) these aren't binary search trees, what Bst almost certainly stands for.
2

Your data declaration states that there are two ways to construct a Bst: with the Empty constructor or with the Node constructor.

-- An empty Bst
bst1 = Empty

-- A Bst containing a single value.
bst2 = Node Empty 42 Empty

-- A Bst containing 3 values, 2 at the root, 1 in the left child and 3 in the right child.
bst3 = Node (Node Empty 1 Empty) 2 (Node Empty 3 Empty)

Comments

0

I'll rewrite your declaration slightly, to use a more idiomatic order of arguments to Node:

data Bst a = Empty | Node a (Bst a) (Bst a)

Empty and Node are what Haskell calls constructors. Constructors can be used two ways:

  1. As functions to construct values of their type;
  2. As patterns in the special pattern matching syntax to analyze and disassemble values of their type.

If we load your type into the ghci interpreter, we can use ghci's :t command to show the types of your constructors:

Ok, modules loaded: Main.
*Main> :t Empty
Empty :: Bst a
*Main> :t Node
Node :: a -> Bst a -> Bst a -> Bst a
*Main> 

So Empty is a constant that has type Bst a for any a, while Node is a function that produces a Bst a given three arguments: an a and two Bst a. So to construct a value of the type, you use one of the constructors, give it the required number of arguments (none in the case of Empty, three for Node), and of the correct type.

Let me stress this bit again: you can use a constructor the same way you can use any expression of the same type as the constructor. So, for example, just like you can partially apply a function in Haskell (apply it to fewer arguments than it takes), you can partially apply a constructor: Node "foo" Empty has type Bst String -> Bst String.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.