[Haskell-beginners] Pattern matching on binary trees

lakshminaras2002 at gmail.com lakshminaras2002 at gmail.com
Sun Sep 5 05:46:49 EDT 2010

The idea behind pattern matching is that you can use any of the data
constructor for the type to dismantle the value coming in.

For depthTree, the type of value expected is Tree a. The Node constructor is
used to dismantle the incoming value into three parts and bind it to
variables x u v. Note here that depthTree accepts only one argument as input
and the type of that value is (Tree a)

When you do not want to dismantle the incoming value, then you would not use
any data constructor. Your function would then become,
    depthTree :: Tree a -> Int
    depthTree x = ..

You cannot use depthTree (x u v) because the compiler would then try to look
for a data constructor x . And in Haskell, data constructor names begin with
a uppercase letter.

You can refer to this page on Haskell wiki
bookhttp://en.wikibooks.org/wiki/Haskell/Pattern_matching for
more information.

On Sun, Sep 5, 2010 at 2:18 PM, Rohit Garg <rpg.314 at gmail.com> wrote:

> Hi,
> I am working on exercises in RWH, chapter 3 and I have a a question
> about the pattern matching in the depth-of-tree question.
> The tree datatype is defined as
> data Tree a = Node a (Tree a) (Tree a)
>            | Empty
>              deriving (Show)
> And to pattern match on it, I need to write
> depthTree (Node x u v) = 1 + max (depthTree u) (depthTree v)
> My question is why do I need to prefix x with Node? Why can't it
> pattern match on depthTree (x u v)? More generally, where do I need to
> put data constructors in pattern matches?
> --
> Rohit Garg
> http://rpg-314.blogspot.com/
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

Lakshmi Narasimhan T V
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100905/50e7abe0/attachment-0001.html

More information about the Beginners mailing list