0

I'm new to Haskell and am currently working on trees. In this, I wanted to create a function, that swaps the elements in a Tree until it becomes a maxheap. This, I would then use for a Heapsort algorithm.

data Bintree a = E | Tree (Bintree a) a (Bintree a) deriving( Eq, Ord, Show )

swaptree:: Bintree Int -> Bintree Int
swaptree (Tree E w E) = (Tree E w E)
swaptree (Tree E w (Tree lr x rr))|((max w x)==w)=(Tree E w (Tree lr x rr))
                              |((max w x)==x)=(Tree E x(swaptree(Tree lr w rr)))
                              |otherwise error "something went wrong or program is bad"
swaptree (Tree (Tree ll v rl) w E)|((max v w)==w)=(Tree (Tree ll v rl) w E)
                              |((max v w)==v)=(Tree (swaptree(Tree ll w rl)) v E)
                              |otherwise error "something went wrong or program is bad"
swaptree (Tree (Tree ll v rl) w (Tree lr x rr) )|((max3 v w x)==w) = (Tree (Tree ll v rl) w (Tree lr x rr)) 
                                            |((max v x)==x)=(Tree (Tree ll v rl) x (swaptree(Tree lr w rr)))
                                            |((max v x)==v)=(Tree(swaptree(Tree ll w rl)) v (Tree lr x rr) )
                                            |otherwise error "something went wrong or program is bad"
swaptree':: Bintree Int -> Bintree Int
swaptree' (Tree E w E) = (Tree E w E)
swaptree' (Tree lub w rub)  = (swaptree(Tree(swaptree lub) w (swaptree rub)))

This yields me this error:

   8:1: error:parse error (possibly incorrect indentation or mismatched brackets)

Now, I looked it up and read, that this usually happens, leSt is used without in, but since I didn't use it I have no Idea how to fix this. I would greatly appreciate any help or tips on how to improve my code!

PS: Please have mercy on me. As I said, I'm currently very bad at Haskell.

2 Answers 2

1

The error was already spotted by Li-yao Xia, and a fix was suggested.

Note that you can also remove the offending line using this style:

swaptree (Tree E w (Tree lr x rr)) | x <= w    = Tree E w (Tree lr x rr)
                                   | otherwise = Tree E x (swaptree (Tree lr w rr))
-- etc.

Indeed, it is weird to check three cases max x w == x, max x w == w, and otherwise. If we do reach the "otherwise" something is really wrong with the definition of max. We can safely ignore that case.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is much better!
1
|otherwise error "something went wrong or program is bad"

should be

|otherwise = error "something went wrong or program is bad"

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.