[Haskell] help with some basic code that doesn't work
Matthew Walton
matthew at alledora.co.uk
Tue Feb 8 04:32:10 EST 2005
pablo daniel rey wrote:
> hello
> i'm new to haskell so i'm sorry if this is a stupid question, but i'm having problems with some basic code.
> the code :
>
> data Maybe Dir = Just Dir | Nothing
> data Dir = Left | Right | Up | Down
> data Piece = Vertical | Horizontal | CodeA | CodeB
>
> flow = [(Horizontal, Left, Left),
> (Horizontal, Right, Right),
> (Vertical, Down, Down),
> (Vertical, Up, Up), ................ etc ]
>
>
> fst :: (a,b,c) -> a
> fst (x,y,z) = x
>
> scnd :: (a,b,c) -> b
> scnd (x,y,z) = y
>
> third :: (a,b,c) -> c
> third (x,y,z) = z
>
> element :: [(Piece, Dir, Dir)] -> Maybe Dir
> element [] = Nothing
> element xs = Just (third (head xs))
>
> chgDir :: Piece -> Dir -> Maybe Dir
> chgDir p d = element (filter (\x -> p == (fst x)) (filter (\x -> d == (scnd x)) flow))
>
>
> the error i get :
>
> Instances of (Eq Dir, Eq Piece) required for definition of chgDir
Because you're using the function (==) to compare two things of type
Piece, Haskell needs to know how to compare them. This information isn't
provided by your type definitions.
(==) works on types which are members of the Eq typeclass. You can
define this instance manually, or, since your type is nice and simple,
you can get Haskell to derive it for you.
data Piece = Vertical | Horizontal | CodeA | CodeB
deriving Eq
similarly
data Dir = Left | Right | Up | Down
deriving Eq
this should sort that problem out.
Incidentally, you don't need to define 'Maybe Dir'. The Maybe type is
built in as 'Maybe a', where 'a' is a parameter which can be any type
(such as Dir). Your functions should work unchanged if you take out your
definition of 'Maybe Dir'.
More information about the Haskell
mailing list