[Haskell-cafe] how to make this work recursive ?

Mike Meyer mwm at mired.org
Sat Feb 28 11:17:37 UTC 2015


On Sat, Feb 28, 2015 at 5:07 AM, Roelof Wobben <r.wobben at home.nl> wrote:

>
> That part I understand .
>
> it's more how I do it here :
>
> Lets say I have this :
>
> data MessageType = Info
>                  | Warning
>                  | Error Int
>   deriving (Show, Eq)
>
> type TimeStamp = Int
>
> data LogMessage = LogMessage MessageType TimeStamp String
>                 | Unknown String
>   deriving (Show, Eq)
>
> data MessageTree = Leaf
>                  | Node MessageTree LogMessage MessageTree
>   deriving (Show, Eq)
>
> Now I have to put all the LogMessages in a binary tree.
> with this signature : insert :: LogMessage -> MessageTree -> MessageTree
>
> I think I need recursion here but I still not see how I can make the
> clauses.
> Normally you can say somethig like this  [] -> 0  or  1 ->   but here it
> seems to be all seperate logMessages
>

Whether you need recursion or not depends on where you're to insert the
message. For instance, you could turn them into a list with:

insert message tree = Node tree message Leaf

Try drawing a few pictures of what that produces, and you'll see why it's
probably not what you want.

You should be able to tell by looking at the MessageTree type that you have
two cases: one where you're passed something matching a Node, and one where
you're passed something that's just a Leaf. The latter can't be recursive,
so it's going to terminate any recursion. Following the advice given to you
for the Hanoi problem, try writing it first.

Then all you have to do is figure out how to handle the case where you're
given a Node instead of a Leaf.  Figuring out where in the MessageTree you
want to insert the Logmessage will probably be required to do that.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20150228/37b45ab2/attachment-0001.html>


More information about the Haskell-Cafe mailing list