4

I'm actually new to Haskell. I've written this code for Queue, but the last line always face this syntax error .

Syntax error in input (unexpected '='). 

I really can't figure out what's wrong :(

module Queue where
data Queue a = Q[a] deriving Show

class QDS q a where
  pop :: q a -> (a, q a)
  push :: q a -> a -> q a
  lengthQS :: q a -> Int
  isEmpty :: q a -> Bool

instance QDS Queue a where
  pop (Q (x:xs)) = (x, (Q xs))
  push (Q x) a = (Q (x ++ [a])) 
  lengthQS (Q x) = length x
  isEmpty q = lengthQS q == 0  -- This line fails
6
  • 2
    Please be sure to tag the language you are using - it is the most important tag. Commented Apr 24, 2015 at 5:04
  • 4
    Your code compiles with FlexibleInstances and MultiParamTypeClasses, which, for future reference, is helpful to include when you post code. Is it possible you used a tab instead of spaces somewhere? Commented Apr 24, 2015 at 5:09
  • @Eric can you make this into an answer so Negar can accept/close this question? Commented Apr 24, 2015 at 9:48
  • @NegarAlinaghi do you really need the type class here? Why not just write the functions directly agains Queue? Commented Apr 24, 2015 at 9:49
  • You might find this useful too: Simple and Efficient Purely Functional Queues and Deques :D Commented Apr 24, 2015 at 9:51

1 Answer 1

1

Solution without compiler extensions:

Remove the type parameter a in both class and instance:

class QDS q where
instance QDS Queue where

and it compiles fine without language extensions.

Need for MultiParamTypeClasses

The reason the compiler wants MultiParamTypeClasses is obvious: Your QDS supplies two type parameter. If you do not include the instance, MultiParamTypeClass is enough.

Need for FlexibleInstances

Without Flexible instances, a concrete declaration like instance QDS Queue Int where compiles fine. You have to ask someone else for a deeper explanation, I can only superficially say a is more flexible then Int.

Why is one parameter enough?

You do not place any constraints on your payload a. To include it is just as unnecessary as for Functor, Foldable etc.

Typeclasses

A word of advice, taken from the comments: With an OOP background, typeclasses give you a false impression of feeling at home. You will rarely need to define a class. The ability to pass functions around is more powerful than using objects (or data constrained to a typeclass for haskell).

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

1 Comment

However, requiring the queue to be parametrized over its element type may not be something you want. It's not necessarily so great if you implement unboxed queues.

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.