P. 1
Haskell Programming Language

Haskell Programming Language

|Views: 157|Likes:
Published by Saira Ali

More info:

Published by: Saira Ali on May 17, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

04/03/2013

pdf

text

original

We can define datatypes that are more complicated that lists. Suppose we want to
define a structure that looks like a binary tree. A binary tree is a structure that has a
single root node; each node in the tree is either a “leaf” or a “branch.” If it’s a leaf, it
holds a value; if it’s a branch, it holds a value and a left child and a right child. Each of
these children is another node. We can define such a data type as:

data BinaryTree a
= Leaf a
| Branch (BinaryTree a) a (BinaryTree a)

In this datatype declaration we say that a BinaryTree of as is either a Leaf
which holds an a, or it’s a branch with a left child (which is a BinaryTree of as), a

52

CHAPTER 4. TYPE BASICS

node value (which is an a), and a right child (which is also aBinaryTreeof as). It is
simple to modify the listLength function so that instead of calculating the length
of lists, it calculates the number of nodes in aBinaryTree. Can you figure out how?
We can call this function treeSize. The solution is given below:

treeSize (Leaf x) = 1
treeSize (Branch left x right) =
1 + treeSize left + treeSize right

Here, we say that the size of a leaf is 1 and the size of a branch is the size of its left
child, plus the size of its right child, plus one.

Exercises

Exercise 4.9 WriteafunctionelementswhichreturnstheelementsinaBinaryTree
in a bottom-up, left-to-right manner (i.e., the first element returned in the left-most leaf,
followed by its parent’s value, followed by the other child’s value, and so on). The re-
sult type should be a normal Haskell list.

Exercise 4.10 Write a fold function for BinaryTrees and rewrite elements in
terms of it (call the new one elements2).

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->