Maximum Clique finder in Haskell - parse error - haskell

I am trying to implement the Bron-Kerbosch algorithm for finding the number of maximum cliques (maximum Clique is a subset of a graph where every two verticies are connected and there is no larger clique containing it)
https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm
Unfortunately, I get an error : "parse error on input 'res' "
And I can't seem to solve it. I have tried to change the tap spaces with normal ones, but it doesn't seem to work. I also don't see any errors? Any ideas?
type Clique = [Vertex]
swarming::Clique->[Vertex]->[Vertex]->[Clique]
swarming R P X =
if null P && null X then [R]
else loop R X
where
loop::[Vertex]->[Vertex]->[Clique]
loop[] _ =[]
loop(v:R') X=
swarming (v:R)(P 'res' v)(X 'res' v)
loop P (v:X)
type Vertex = Int
class Graph g where
size ::g->Int
verticies ::g->[Vertex]
connected ::g->Vertex->Vertex->Bool
bron::Graph g=>g->[Clique]
bron g = swarming[] (verticies g) []
where
swarming R P X =
if null P && null X then [R]
else loop R X
where
loop::[Vertex]->[Vertex]->[Clique]
loop[] _ =[]
loop(v:R) X=
swarming (v:R)(P 'res' v)(X 'res' v)
loop P (v:X)
res::[Vertex]->Vertex->[Vertex]
res vs v = filter(connected g v) vs

As I can see there is a bit more wrong with your code than just the error you get:
first of all as the comment already says ' are reserved for single characters Char, the syntax you are looking for is `res`.
secondly I saw you are using tabs, newer versions of the ghc compiler will warn you about that, usually nowadays people use spaces (this is mostly a matter of taste and it is up to you)
I have slightly reordered your code and modified it in such a way it compiles. The undefined will raise a run-time error, but this state is better than a non-compiling one.
type Clique = [Vertex]
type Vertex = Int
class Graph g where
size :: g -> Int
vertices :: g -> [Vertex]
connected :: g -> Vertex -> Vertex -> Bool
I usually organize my code in a way that type/data/class declarations are on top of my file and the rest below that.
Syntax wise the next error you have is using upper case letters for variable names - this is not allowed in haskell. Types start with upper case variables with lower case.
bron is a tricky function and I honestly cannot quite figure out what you want to do there are two things that make this hard to figure out.
You have 'variables' r and r in both swarming and loop - it seems that they should be not the same, whereas p should be always the same.
Name shadowing is not a syntactic problem but a logical, it makes it easier if two different things have not the same name.
I see
loop ... = swarming
loop
this is invalid haskell syntax - what are you going to do with swarming it is not used in the following parts of the code, use let … in to stitch those two lines together
here is the rest of your code bron with a compiling but incomplete implementation
bron :: Graph g => g -> [Clique]
bron g = swarming [] (vertices g) []
where res :: [Vertex] -> Vertex -> [Vertex]
res vs v = filter (connected g v) vs
swarming :: Clique -> [Vertex] -> [Vertex] -> [Clique]
swarming r [] [] = [r]
swarming r p x = loop r x
where loop :: [Vertex] -> [Vertex] -> [Clique]
loop [] _ = []
loop (v:r) x = undefined
-- let sw = swarming (v:x) (p `res` v) (x `res` v)
-- in loop ??

Related

why is this function non exhaustive?

Compiler warns the function "insert" is non-exhaustive in the following code:
data Set a = Empty | Set a (Set a) (Set a) deriving (Eq, Show)
insert :: (Ord a) => a -> Set a -> Set a
insert x Empty = Set x Empty Empty
insert x (Set v l r)
| x <= v = Set v (insert x l) r
| v < x = Set v l (insert x r)
-- | otherwise = Set x Empty Empty
main :: IO ()
main = do
let x = insert (5::Int) Empty
print x
GHC reports this
test.hs:4:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘insert’: Patterns not matched: _ (Set _ _ _)
If I uncomment the last line (it's commented out now) in the function, GHC does not report any warning. So I guess GHC thinks the guards are non-exhaustive. But why? If x and v are instances of Ord, then I guess
(x <= v) and (v < x) are all the possible outcomes of comparison?
What if I define this instance:
newtype Fuzzy = Fuzzy Double
instance Eq Fuzzy where
Fuzzy a == Fuzzy b = abs (a-b) < 0.1
instance Ord Fuzzy where
Fuzzy a < Fuzzy b = a < b-0.1
Fuzzy a <= Fuzzy b = a <= b
Then for e.g. v = Fuzzy 0, x = Fuzzy 0.1, you have (x <= v) = (0.1 <= 0) which is false, but (v < x) = (0 < 0) which is also false. Hence both of your guards will fail.
This isn't so hypothetical, in fact Double itself already has such behaviour in degenerate values:
Prelude> sqrt (-1) < 0
False
Prelude> 0 <= sqrt (-1)
False
Now, it's very debatable whether these are really good, even well-formed Ord instances, but at any rate the compiler can't guarantee something like that won't happen. Hence it also can't make the assumption that not (x <= v) implies v < x, so what should happen if neither is fulfilled?
The usual thing to do if you assume all Ord instances you received are docile is to just make the second clause already catch-all:
insert x (Set v l r)
| x <= v = Set v (insert x l) r
| otherwise = Set v l (insert x r)
However, depending on your philosophy, your original code might actually be better. With the catch-all in the second, you just defer the weirdness if someone hands you NaN values. This makes it all the more difficult to understand what's going on.
If tend to deliberately not complete patterns with “impossible cases” in experimental code: this way I'll at least always get a clear runtime error telling me at which point in the code things go awry. Once the code essentially works and you want to make it production-ready, you can then toss in -Wall and learn about all spots where you'd better add some explicit handling of pathological behaviour like the one I mentioned.

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
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").
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) ]

Is it possible to generalise equations in Haskell?

Apologies for my poor wording of the question. I've tried searching for an answer but not knowing what to search is making it very difficult to find one.
Here is a simple function which calculates the area of a triangle.
triangleArea :: Float -> Float -> Float -> Float
triangleArea a b c
| (a + b) <= c = error "Not a triangle!"
| (a + c) <= b = error "Not a triangle!"
| (b + c) <= a = error "Not a triangle!"
| otherwise = sqrt (s * (s - a) * (s - b) * (s - c))
where s = (a + b + c) / 2
Three lines of the function have been taken up for the purposes of error checking. I was wondering if these three lines could be condensed into one generic line.
I was wondering if something similar to the following would be possible
(arg1 + arg2) == arg3
where Haskell knows to check each possible combination of the three arguments.
I think #behzad.nouri's comment is the best. Sometimes doing a little math is the best way to program. Here's a somewhat overdone expansion on #melpomene's solution, which I thought would be fun to share. Let's write a function similar to permutations but that computes combinations:
import Control.Arrow (first, second)
-- choose n xs returns a list of tuples, the first component of each having
-- n elements and the second component having the rest, in all combinations
-- (ignoring order within the lists). N.B. this would be faster if implemented
-- using a DList.
choose :: Int -> [a] -> [([a],[a])]
choose 0 xs = [([], xs)]
choose _ [] = []
choose n (x:xs) =
map (first (x:)) (choose (n-1) xs) ++
map (second (x:)) (choose n xs)
So..
ghci> choose 2 [1,2,3]
[([1,2],[3]),([1,3],[2]),([2,3],[1])]
Now you can write
triangleArea a b c
| or [ x + y <= z | ([x,y], [z]) <- choose 2 [a,b,c] ] = error ...
This doesn't address the question of how to shorten your error checking code, but you may be able to limit how often you repeat it by defining some new types with invariants. This function needs error checking because you can't trust the user to supply Float triples that make a reasonable triangle, and if you continue to define functions this way then every triangle-related function you write would need similar error checks.
However, if you define a Triangle type, you can check your invariants only once, when a triangle is created, and then all other functions will be guaranteed to receive valid triangles:
module Triangle (Triangle(), mkTriangle, area) where
data Triangle a = Triangle a a a deriving Show
mkTriangle :: (Num a, Ord a) => a -> a -> a -> Either String (Triangle a)
mkTriangle a b c
| a + b <= c = wrong
| a + c <= b = wrong
| b + c <= a = wrong
| otherwise = Right $ Triangle a b c
where wrong = Left "Not a triangle!"
area :: Floating a => Triangle a -> a
area (Triangle a b c) = sqrt (s * (s - a) * (s - b) * (s - c))
where s = (a + b + c) / 2
Here we export the Triangle type, but not its constructor, so that the client must use mkTriangle instead, which can do the required error checking. Then area, and any other triangle functions you write, can omit the checks that they are receiving a valid triangle. This general pattern is called "smart constructors".
Here are two ideas.
Using existing tools, you can generate all the permutations of the arguments and check that they all satisfy a condition. Thus:
import Data.List
triangleArea a b c
| any (\[x, y, z] -> x + y <= z) (permutations [a,b,c])
= error "Not a triangle!"
| otherwise = {- ... -}
This doesn't require writing very much additional code; however, it will search some permutations you don't care about.
Use the usual trick for choosing an element from a list and the left-overs. The zippers function is one I use frequently:
zippers :: [a] -> [([a], a, [a])]
zippers = go [] where
go b [] = []
go b (v:e) = (b, v, e) : go (v:b) e
We can use it to build a function which chooses only appropriate triples of elements:
triples :: [a] -> [(a, a, a)]
triples xs = do
(b1, v1, e1) <- zippers xs
(b2, v2, e2) <- zippers e1
v3 <- b1 ++ b2 ++ e2
return (v1, v2, v3)
Now we can write our guard like in part (1), but it will only consider unique pairings for the addition.
triangleArea a b c
| any (\(x, y, z) -> x + y <= z) (triples [a,b,c])
= error "Not a triangle!"
| otherwise = {- ... -}

Haskell Data.Vector, huge memory leak

I am trying to make a basic 2D engine with haskell and the SDL1.2 bindings (for fun, I am just learning).
Ideally the world is to be procedurally generated, chunk by chunk, allowing free exploration.
Right now my chunk is composed of 200*200 tiles which I represent using a type:
Mat [Tile] = Vec.Vector (Vec.Vector [Tile])
and these functions:
fromMat :: [[a]] -> Mat a
fromMat xs = Vec.fromList [Vec.fromList xs' | xs' <- xs]
(§) :: Mat a -> (Int, Int) -> a
v § (r, c) = (v Vec.! r) Vec.! c
I am using cyclic list of tiles in order to allow for sprite animation, and later for dynamic behaviour.
Each frame of the game loop, the program reads the part of the vector relevant to the current camera position, display the corresponding tiles and return a new vector in which every of these cyclic lists has been replaced by it's tail.
Here is the code responsible for this:
applyTileMat :: Chunk -> SDL.Surface -> SDL.Surface -> IO Chunk
applyTileMat ch src dest =
let m = chLand $! ch
(x,y) = chPos ch
wid = Vec.length (m Vec.! 0) - 1
hei = (Vec.length m) - 1
(canW,canH) = canvasSize ch in
do sequence $ [ applyTile (head (m § (i,j))) (32*(j-x), 32*(i-y)) src dest | i <- [y..(y+canH)], j <- [x..(x+canW)]]
m' <-sequence $ [sequence [(return $! tail (m § (i,j))) | j <- [0..wid]] | i <- [0..hei]] --weird :P
return ch { chLand = fromMat m' }
the first sequence does the display part, the second one returns the new vector m'.
At first I was using the following comprehension to get m'
let !m' = [id $! [(tail $! (m § (i,j))) | j <- [0..wid]] | i <- [0..hei]]
but doing so results in ever increasing memory usage. I think it has to do with lazy evaluation preventing the data to be properly garbage collected, but I don't really understand why.
In this particular case, it doesn't really mater since I have to look at the whole vector. But I don't know how I should do if I wanted to only "update" part of my chunk each frame, thus making a new chunk with only part of the data from the previous one.
I am probably not using Data.Vector the way it's intended, but it's the simplest data structure I found with O(n) random access.
The whole code is there:
https://github.com/eniac314/wizzard/blob/master/tiler.hs
The problem is indeed that vectors are lazy in the elements. First, let's look at why your example doesn't work.
let !m' = [id $! [(tail $! (m § (i,j))) | j <- [0..wid]] | i <- [0..hei]]
The bang pattern in !m doesn't do much. All ! does is ensure that a variable is a constructor or a lambda, instead of a function application. Here !m can be discerned to be either an [] or a (:) without evaluating any elements. Similarly, the įd $!-s don't force any actual elements of the inner lists.
return ch { chLand = fromMat m' }
fromMat is the next culprit. fromMat doesn't force the inner vectors, and also doesn't force the elements. As a result, references to old vectors stick around in the thunks indefinitely.
Often the correct solution is to import Control.DeepSeq, and use force or $!! to fully evaluate vectors. Unfortunately, we can't do that here because of the cyclic lists (trying to force one results in an infinite loop).
What we really need is a function that brings all the elements of a vector to weak head normal form:
whnfElements :: Vector a -> Vector a
whnfElements v = V.foldl' (flip seq) () v `seq` v
We can use this to define a strict map for vectors:
vmap' :: (a -> b) -> Vector a -> Vector b
vmap' f = whnfElements . V.map f
Now updating becomes:
update :: Mat [Tile] -> Mat [Tile]
update = (vmap' . vmap') tail

Simplifying some Haskell code

So I'm working on a minimax implementation for a checkers-like game to help myself learn Haskell better. The function I'm having trouble with takes a list for game states, and generates the list of immediate successor game states. Like checkers, if a jump is available, the player must take it. If there's more than one, the player can choose.
For the most part, this works nicely with the list monad: loop over all the input game states, loop over all marbles that could be jumped, loop over all jumps of that marble. This list monad nicely flattens all the lists out into a simple list of states at the end.
The trick is that, if no jumps are found for a given game state, I need to return the current game state, rather than the empty list. The code below is the best way I've come up with of doing that, but it seems really ugly to me. Any suggestions on how to clean it up?
eHex :: Coord -> Coord -- Returns the coordinates immediately to the east on the board
nwHex :: Coord -> Coord -- Returns the coordinates immediately to the northwest on the board
generateJumpsIter :: [ZertzState] -> [ZertzState]
generateJumpsIter states = do
ws <- states
case children ws of
[] -> return ws
n#_ -> n
where
children ws#(ZertzState s1 s2 b p) = do
(c, color) <- occupiedCoords ws
(start, end) <- [(eHex, wHex), (wHex, eHex), (swHex, neHex),
(neHex, swHex), (nwHex, seHex), (seHex, nwHex)]
if (hexOccupied b $ start c) && (hexOpen b $ end c)
then case p of
1 -> return $ ZertzState (scoreMarble s1 color) s2
(jumpMarble (start c) c (end c) b) p
(-1) -> return $ ZertzState s1 (scoreMarble s2 color)
(jumpMarble (start c) c (end c) b) p
else []
EDIT: Provide example type signatures for the *Hex functions.
The trick is that, if no jumps are found for a given game state, I need to return the current game state, rather than the empty list.
Why? I've written minimax several times, and I can't imagine a use for such a function. Wouldn't you be better off with a function of type
nextStates :: [ZertzState] -> [Maybe [ZertzState]]
or
nextStates :: [ZertzState] -> [[ZertzState]]
However if you really want to return "either the list of next states, or if that list is empty, the original state", then the type you want is
nextStates :: [ZertzState] -> [Either ZertzState [ZertzState]]
which you can then flatten easily enough.
As to how to implement, I recommend defining a helper function of type
[ZertzState] -> [(ZertzState, [ZertzState])]
and than you can map
(\(start, succs) -> if null succs then Left start else Right succs)
over the result, plus various other things.
As Fred Brooks said (paraphrasing), once you get the types right, the code practically writes itself.
Don't abuse monads notation for list, it's so heavy for nothing. Moreover you can use list comprehension in the same fashion :
do x <- [1..3]
y <- [2..5] <=> [ x + y | x <- [1..3], y <- [2..5] ]
return x + y
now for the 'simplification'
listOfHex :: [(Coord -> Coord,Coord -> Coord)]
listOfHex = [ (eHex, wHex), (wHex, eHex), (swHex, neHex)
, (neHex, swHex), (nwHex, seHex), (seHex, nwHex)]
generateJumpsIter :: [ZertzState] -> [ZertzState]
generateJumpsIter states =
[if null ws then ws else children ws | ws <- states]
where -- I named it foo because I don t know what it do....
foo True 1 = ZertzState (scoreMarble s1 color) s2
(jumpMarble (start c) c (end c) b) p
foo True (-1) = ZertzState s1 (scoreMarble s2 color)
(jumpMarble (start c) c (end c) b) p
foo False _ = []
foo _ _ = error "Bleh"
children ws#(ZertzState s1 s2 b p) =
[ foo (valid c hex) p | (c, _) <- occupiedCoords ws, hex <- listOfHex ]
where valid c (start, end) =
(hexOccupied b $ start c) && (hexOpen b $ end c)
The let in the let in list commprehension at the top bother me a little, but as I don't have all the code, I don't really know how to do it in an other way. If you can modify more in depth, I suggest you to use more combinators (map, foldr, foldl' etc) as they really reduce code size in my experience.
Note, the code is not tested, and may not compile.

Resources