Tilman Zuckmantel
Tilman Zuckmantel

Reputation: 720

Having trouble with matching type in Haskell (generateTrees)

i am sitting with two guys on a haskell project and we have quite a bit of trouble with the following code:

I try to give you all the necessary information:

From the module Types.hs:

class Game g s | g -> s where
  findPossibleMoves :: Player -> g -> [(s,g)]
  identifyWinner :: g -> Player -> Maybe Player 

data Player = Player1 | Player2 deriving (Eq,Ord)

and here is the code we want to implement:

generateGameTree :: Game g s => g -> Player -> Tree (g,Player) s
generateGameTree g p = ([ Node ((snd x),p) [] | x <- (findPossibleMoves p g )])

So we try to get this thing compiled but it wont work . It might be important to know how a tree looks like so thats the definition:

data Tree v e  = Node v [(e,Tree v e)] deriving (Show,Eq,Ord)

We allready know, that the returntype of the function and our returntype doesn't match, but there must be another mistake in this.

We would appreciate any help , thanks in advance

Upvotes: 1

Views: 102

Answers (2)

Tilman Zuckmantel
Tilman Zuckmantel

Reputation: 720

To whom it may interest:

This works now without compiler error:

generateGameTree g p = Node (g,p) [ ((fst x),generateGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ]

Upvotes: 0

gallais
gallais

Reputation: 12123

You may want to split this operation into two smaller ones:

A generic unfold function first which, given a seed of type s and a function computing one layer of tree generates a whole tree by repeatedly calling itself on the next generation of seeds. This definition would have type:

unfold :: (s -> (v, [(e,s)])) -> s -> Tree v e
unfold next seed = _fillThisIn

You can then use this function to define your generateGameTree. The intuition behind using unfold is that the seed of type s represents the state of the game and the function next computes the possible new states after one move (together with the v and e "outputs").

Upvotes: 1

Related Questions