0
votes

I am working on a homework and need some help The task: In the first step I need to define a new type class for a overloaded function "genDrop". It should behave like "drop" (for Int), but not limited to Int. In a second step it should be instantiated for types Int, Nat, PosNat and Int'.

So here my code:

class GenDrop a where
     genDrop :: a -> [a] -> [a]


    instance GenDrop Int where
        genDrop 0 s = s
        genDrop n (_:s) | n>0 = genDrop (n-1) s
        genDrop _ [] = []

    instance GenDrop Nat where
        genDrop Zero s = s
        genDrop (Succ n) (_:s)  = genDrop n s
        genDrop _ [] = []

    instance GenDrop PosNat where
        genDrop One (_:s)= s
        genDrop (Succ' n) (_:s) = genDrop n s
        genDrop _ [] = []

    instance GenDrop Int' where
        genDrop Zero' s = s
        genDrop (Plus n) (_:s) = genDrop n s
        genDrop (Minus n) s = s
        genDrop _ [] = []

But on compiling i get an error:

parse error on input 'instance'
instance GenDrop Int where

I can't figure out whats wrong.

1
It might not matter but here the definitions: data Nat = Zero | Succ Nat data PosNat = One | Succ' PosNat data Int' = Zero' | Plus PosNat | Minus PosNat - Dortmunder
Is the indentation here the same as in your code? You need to move the instance definitions outside the class declaration. - Lee
You need to indent your instances so that the word instance starts on the same column as the word class, i.e. at the very beginning of the line. - chi
Great! Thats it! It drove me nearly crazy. Thanks! - Dortmunder

1 Answers

2
votes

The instance declarations are not part of the class declaration: don't indent them as if they are. Indentation matters in Haskell.

Here is the corrected code:

class GenDrop a where
    genDrop :: a -> [a] -> [a]

instance GenDrop Int where
    genDrop 0 s = s
    genDrop n (_:s) | n>0 = genDrop (n-1) s
    genDrop _ [] = []

instance GenDrop Nat where
    genDrop Zero s = s
    genDrop (Succ n) (_:s)  = genDrop n s
    genDrop _ [] = []

instance GenDrop PosNat where
    genDrop One (_:s)= s
    genDrop (Succ' n) (_:s) = genDrop n s
    genDrop _ [] = []

instance GenDrop Int' where
    genDrop Zero' s = s
    genDrop (Plus n) (_:s) = genDrop n s
    genDrop (Minus n) s = s
    genDrop _ [] = []