Parse error in where - haskell

In this code
neighbours :: CityMap -> District -> [District]
neighbours (CM (_,rs)) b = mapMaybe neighbour rs
where neighbour (p,q)
| b == p = Just q --parse error (possibly incorrect indentation or mismatched brackets)
| b == q = Just p
| otherwise = Nothing
i have parse in first «|»

The guards have to be indented further than the name of the function they're part of, for example:
neighbours :: CityMap -> District -> [District]
neighbours (CM (_,rs)) b = mapMaybe neighbour rs
where neighbour (p,q)
| b == p = Just q
| b == q = Just p
| otherwise = Nothing
This is because following the where, you're defining a (local) function neighbour, which has to also follow the layout rule; if the guard is further to the left, it's not a continuation of the definition of neighbour. You'd get the same error in a file that looked like this:
neighbour (p,q)
| b == p = Just q

Related

Propositional logic in haskell

I have the following data types
data Prop =
Var Name
| Neg Prop
| Conj Prop Prop
| Disy Prop Prop
| Impl Prop Prop
| Syss Prop Prop deriving Show -- if and only if
-- And the following
type Name = String
type State = (Name, Bool) -- The state of a proposition, Example ("P", True), ("Q", True)
type States = [State] -- A list of states, [("P", True), ("Q", False), ...]
type Row = (States, Bool) -- A row of the table. ([("P", True), ("Q", False), ...], True)
type Table = [Row]
The case is that I want to generate all the possible states of a proposition
P, Q, R
1 1 1
1 1 0
1 0 1
...
To do this, I create auxiliary functions to gradually build the states
-- Get all the atoms of a proposition
varList :: Prop -> [Name]
varList (Var p) = [p]
varList (Neg p) = varList p
varList (Conj p q) = varList p ++ varList q
varList (Disy p q) = varList p ++ varList q
varList (Impl p q) = varList p ++ varList q
varList (Syss p q) = varList p ++ varList q
--Power set to get all values
conjPoten :: Eq a => [a] -> [[a]]
conjPoten [] = [[]]
conjPoten (x:xs) = map (x: ) pt `union` pt
where
pt = conjPoten xs
-- Give value to a proposition, "P" -> True, "" -> False
giveValue:: Name -> Bool
giveValue p = p /= []
-- Generate a State, "P" -> ("P",True), "" -> ("",False)
generateState :: Name -> State
generateState p = (p , daValor p)
-- The function that I want
generateStates:: [Name] -> States
generateStates p = [(a,True) | a <-p]
This, of course, is a test to verify that "it works", because if
generateStates ["P","Q", "R"] = [("P",True),("Q",True),("R",True)]
I did this thinking that in the power set we are going to have cases like ["P","Q","R"] and ["P","Q"], that is, there is not going to be "R". So the intention is that
["P","Q","R"] gives us [("Q",True),("P",True),("R",True)] and
["P","Q"] gives us [("Q",True),("P",True),("R",False)]
But from here I have two questions
The first is, that I have to modify the second element of the tuple, so what I came up with was
generateStates :: [Name] -> States
generateStates p = [ (a, b) | a<- p, a<- giveValue p]
The main error that the prelude marks me is:
Couldn't match type ‘[Char]’ with ‘Char’
Which I understand, because p is a list and giveValue works with a Name, not with a list of Names
So my question is: How do I get that p out of a Name? and that it does not stay as a list of Name
I tried to do it like
generateStates :: [Name] -> States
generateStates [p] = [ (p, b) | a<- giveValue p]
But that tells me:
Couldn't match expected type ‘[Bool]’ with actual type ‘Bool’
Which, now I don't understand, plus it tells me there aren't enough patterns
Why does this happen?
The other question is that, having
generateStates :: [Name] -> States
generateStates p = [ (a, True) | a<-p]
and try it with
generateStates ["P","Q"] would only give me [("Q",True),("P",True)]
But we have P, Q and R, so I'm missing the ("R", False)
But since it is in the arguments that we pass, it cannot add it to the list
Where do I get that R? those missing variables?
Thanks!
To change the tuple, you really create a new one, as they are not mutable. You could create a function using pattern matching. The below function works on pairs (tuples with two elements).
modTuple (firstValue, secondValue) updatedValue = (firstValue, updatedValue)
Alternatively you could access the members of the tuple with the built-in fst and snd to access the first and second elements, and create a new tuple.
You can use pattern matching to access individual elements of a list, and build up States recursively. I.e.
generateStates [] = []
generateStates (p:ps) = (p, giveValue p):(generateStates ps)

Haskell, why do I get a prelude undefined error?

this is an exercise where I have to create my own universe of things in Haskell for a logic course. This was given to us already:
data Thing = A | B | C | D | E deriving (Eq,Show)
things :: [Thing]
things = [ A, B, C, D, E ]
data Colour = Amber | Blue deriving Eq
colour :: Thing -> Colour
colour A = Amber
colour B = Amber
colour C = Amber
colour D = Blue
colour E = Amber
data Shape = Square | Disc deriving Eq
shape :: Thing -> Shape
shape A = Square
shape B = Square
shape C = Disc
shape D = Square
shape E = Square
data Size = Big | Small deriving Eq
size :: Thing -> Size
size A = Big
size B = Big
size C = Big
size D = Big
size E = Small
data Border = Thin | Thick deriving Eq
border :: Thing -> Border
border A = Thick
border B = Thin
border C = Thick
border D = Thick
border E = Thick
type Predicate u = u -> Bool
isAmber :: Predicate Thing
isAmber x = colour x == Amber
isBlue :: Predicate Thing
isBlue x = colour x == Blue
isSquare :: Predicate Thing
isSquare x = shape x == Square
isDisc :: Predicate Thing
isDisc x = shape x == Disc
isBig :: Predicate Thing
isBig x = size x == Big
isSmall :: Predicate Thing
isSmall x = size x == Small
hasThinBorder :: Predicate Thing
hasThinBorder x = border x == Thin
hasThickBorder :: Predicate Thing
hasThickBorder x = border x == Thick
The following function was also given as an example of predicate negation :
neg :: Predicate u -> Predicate u
(neg a) x = not (a x)
I have to write 2 functions, one for conjunction (only true & true = true, all else is false) and disjunction (only false & false = true). I was pretty sure that this was correct, but i get the prelude undefined error when I call:
(|:|) :: Predicate u -> Predicate u -> Predicate u
(a |:| b) x = (a x) && (b x)
(&:&) :: Predicate u -> Predicate u -> Predicate u
(a &:& b) x = (a x) || (b x)
(|=) :: Predicate Thing -> Predicate Thing -> Bool
a |= b = [thinga | thinga <- things, a thinga] == [thingb | thingb <- things, b thingb, a thingb]
(|/=) :: Predicate Thing -> Predicate Thing -> Bool
a |/= b = not (a |= b)
But also, the instructions say that calling the following should work, and i do not understand how, since the x formal parameter is never used...
isBig &:& isAmber |= isDisc
That should return either true or false apparently
Example of Error
*Main> :reload
Ok, one module loaded.
*Main> isSmall |= isDisc
False
*Main> (neg isAmber) C
False
*Main> (isBig &:& isAmber) |= isDisc
*** Exception: Prelude.undefined
CallStack (from HasCallStack):
error, called at libraries\base\GHC\Err.hs:79:14 in base:GHC.Err
undefined, called at things.hs:89:15 in main:Main
I'm focusing on this part:
and i do not understand how, since the x formal parameter is never
used...
isBig &:& isAmber |= isDisc
That should return either true or false apparently
The value of x is chosen by |=, which will call both predicates isBig &:& isAmber and isDisc with all the x in list things.
Expanding the definitions:
isBig &:& isAmber |= isDisc
= -- according to the definition of |=
[thinga | thinga <- things, (isBig &:& isAmber) thinga]
==
[thingb | thingb <- things, isDisc thingb, (isBig &:& isAmber) thingb]
= -- according to the definition of &:&
[thinga | thinga <- things, isBig thinga && isAmber thinga]
==
[thingb | thingb <- things, isDisc thingb, isBig thingb && isAmber thingb]
=
[ A, B, C ] -- i.e., list of all things which are both big and amber
==
[ C ] -- i.e., list of all things which are discs, big, and amber
=
False -- the two lists are not the same list
So, it's thinga and thingb that are passed as x. Those variables, in turn, assume all the values inside the list things, i.e. [A,B,C,D,E].

How to get a solution to a puzzle having a function that gives the next possible steps in Haskell

I'm solving the Brigde and torch problem
in Haskell.
I wrote a function that given a state of the puzzle, as in which people have yet to cross and those who have crossed, gives back a list of all possible moves from one side to the other (moving two people forwards and one person backwards).
module DarkBridgeDT where
data Crossing = Trip [Float] [Float] Float deriving (Show)
data RoundTrip = BigTrip Crossing Crossing deriving (Show)
trip :: [Float] -> [Float] -> Float -> Crossing
trip x y z = Trip x y z
roundtrip :: Crossing -> Crossing -> RoundTrip
roundtrip x y = BigTrip x y
next :: Crossing -> [RoundTrip]
next (Trip [] _ _) = []
next (Trip (a:b:[]) s _ )
|a>b = [BigTrip (Trip [] (a:b:s) a) (Trip [] [] 0)]
|otherwise = [BigTrip (Trip [] (b:a:s) b) (Trip [] [] 0)]
next (Trip d s _) = [BigTrip (Trip [x,z] (i:j:s) j) b | i <- d, j <- d, i < j, x <- d, z <- d, x < z, z /= i, z /= j, x /= z, x /= i, x /= j, b <- (back [x,z] (i:j:s))]
where
back [] s = []
back d s = [Trip (i:d) (filter (/= i) s) i | i <- s]
Now I need a function that given a state as the one above and a maximum amount of time gives back all possible solutions to the puzzle in less than that given time.
All I have for that is this:
cross :: Crossing -> Float -> [[RoundTrip]]
cross (Trip [] _ _) _ = []
cross (Trip _ _ acu) max
| acu > max = []
cross (Trip a b acu) max = map (cross (map (crec) (next (Trip a b acu)) acu)) max
where
crec (BigTrip (Trip _ _ t1) (Trip a b t2)) acu = (Trip a b (t1+t2+acu))
Of course that doesn't compile, the 5th line is the one that's driving me insane. Any input?
Edit:
The cross function is meant to apply the next function to every result of the last nextfunction called.
If the first result of next was something like: [A,B,C,D] then it would call next on A B C and D to see if any or all of those get to a solution in less than max (A B C and D would be Crossings inside which contain the floats that are the time that ads up and is compared to max).
My data structure is
Crossing: Contains the first side of the bridge (the people in it represented by the time they take to cross the bridge) the other side of the bridge (the same as the other) and a time that represents the greatest time that last crossed the bridge (either the greatest of the two in the first crossing or the only one in the second) or the amount of time acumulated crossing the bridge (in the cross function).
RoundTrip: Represents two crossings, the first and the second, the one getting to safety and the one coming back to danger.
cross (Trip [1,2,5,10] [] 0) 16 should give an empty list for there is no solution that takes less than 17 minutes (or whatever time unit).
cross (Trip [1,2,5,10] [] 0) 17 should give the normal solution to the puzzle as a list of roundtrips.
I hope that makes it clearer.
Edit2:
I finally got it. I read Carsten's solution before I completed mine and we laid it out practically the same. He used fancier syntax and more complex structures but it's really similar:
module DarkBridgeST where
data Torch = Danger | Safety deriving (Eq,Show)
data State = State
[Float] -- people in danger
[Float] -- people safe
Torch -- torch position
Float -- remaining time
deriving (Show)
type Crossing = [Float]
classic :: State
classic = State [1,2,5,10] [] Danger 17
next :: State -> [Crossing] -- List all possible moves
next (State [] _ _ _) = [] -- Finished
next (State _ [] Safety _) = [] -- No one can come back
next (State danger _ Danger rem) = [[a,b] | a <- danger, b <- danger, a /= b, a < b, max a b <= rem]
next (State _ safe Safety rem) = [[a] | a <- safe, a <= rem]
cross :: State -> Crossing -> State -- Crosses the bridge depending on where the torch is
cross (State danger safe Danger rem) cross = State (taking cross danger) (safe ++ cross) Safety (rem - (maximum cross))
cross (State danger safe Safety rem) cross = State (danger ++ cross) (taking cross safe) Danger (rem - (maximum cross))
taking :: [Float] -> [Float] -> [Float]
taking [] d = d
taking (x:xs) d = taking xs (filter (/=x) d)
solve :: State -> [[Crossing]]
solve (State [] _ _ _) = [[]]
solve sf = do
c <- next sf
let sn = cross sf c
r <- solve sn
return (c:r)
All in all thanks everyone. I'm new to Haskell programming and this helped me understand a lot of things. I hope this post can also help someone starting haskell like me one day :)
I'm not going to leave much of your code intact here.
The first problems are with the data structures. Crossing doesn't actually represent anything to do with crossing the bridge, but the state before or after a bridge crossing. And you can't use RoundTrip because the number of bridge crossings is always odd.
I'm renaming the data structure I'm actually keeping, but I'm not keeping it unmodified.
data Bank = Danger | Safety deriving (Eq,Show)
data PuzzleState = PuzzleState
[Float] -- people still in danger
[Float] -- people on the safe bank
Bank -- current location of the torch
Float -- remaining time
type Crossing = ([Float],Bank)
Modifying/writing these functions is left as an exercise for the reader
next :: PuzzleState -> [Crossing] -- Create a list of possible crossings
applyCrossing :: PuzzleState -> Crossing -> PuzzleState -- Create the next state
Then something like this function can put it all together (assuming next returns an empty list if the remaining time is too low):
cross (PuzzleState [] _ _ _) = [[]]
cross s1 = do
c <- next s1
let s2 = applyCrossing s1 c
r <- cross s2
return $ c : r
Just for the fun, an approach using a lazy tree:
import Data.List
import Data.Tree
type Pawn = (Char, Int)
data Direction = F | B
data Turn = Turn {
_start :: [Pawn],
_end :: [Pawn],
_dir :: Direction,
_total :: Int
}
type Solution = ([String], Int)
-- generate a tree
mkTree :: [Pawn] -> Tree Turn
mkTree p = Node{ rootLabel = s, subForest = branches s }
where s = Turn p [] F 0
-- generates a node for a Turn
mkNode :: Turn -> Tree Turn
mkNode t = Node{ rootLabel = t, subForest = branches t }
-- next possible moves
branches :: Turn -> [Tree Turn]
-- complete
branches (Turn [] e d t) = []
-- moving forward
branches (Turn s e F t) = map (mkNode.turn) (next s)
where
turn n = Turn (s\\n) (e++n) B (t+time n)
time = maximum . map snd
next xs = [x| x <- mapM (const xs) [1..2], head x < head (tail x)]
-- moving backward
branches (Turn s e B t) = map (mkNode.turn) e
where
turn n = Turn (n:s) (delete n e) F (t+time n)
time (_,b) = b
solve :: Int -> Tree Turn -> [Solution]
solve limit tree = solve' [] [] limit tree
where
solve' :: [Solution] -> [String] -> Int -> Tree Turn -> [Solution]
solve' sols cur limit (Node (Turn s e d t) f)
| and [t <= limit, s == []] = sols ++ [(cur++[step],t)]
| t <= limit = concat $ map (solve' sols (cur++[step]) limit) f
| otherwise = []
where step = "[" ++ (v s) ++ "|" ++ (v e) ++ "]"
v = map fst
Then you you can get a list of solutions:
solve 16 $ mkTree [('a',2), ('b',4), ('c',8)]
=> [(["[abc|]","[c|ab]","[ac|b]","[|bac]"],14),(["[abc|]","[c|ab]","[bc|a]","[|abc]"],16),(["[abc|]","[b|ac]","[ab|c]","[|cab]"],14),(["[abc|]","[a|bc]","[ba|c]","[|cab]"],16)]
Or also generate a tree of solutions:
draw :: Int -> Tree Turn -> Tree String
draw limit (Node (Turn s e d t) f)
| t > limit = Node "Time Out" []
| s == [] = Node ("Complete: " ++ step) []
| otherwise = Node step (map (draw limit) f)
where step = "[" ++ (v s) ++ "|" ++ (v e) ++ "]" ++ " - " ++ (show t)
v = map fst
Then:
putStrLn $ drawTree $ draw 16 $ mkTree [('a',2), ('b',4), ('c',8)]
Will result in:
[abc|] - 0
|
+- [c|ab] - 4
| |
| +- [ac|b] - 6
| | |
| | `- Complete: [|bac] - 14
| |
| `- [bc|a] - 8
| |
| `- Complete: [|abc] - 16
|
+- [b|ac] - 8
| |
| +- [ab|c] - 10
| | |
| | `- Complete: [|cab] - 14
| |
| `- [cb|a] - 16
| |
| `- Time Out
|
`- [a|bc] - 8
|
+- [ba|c] - 12
| |
| `- Complete: [|cab] - 16
|
`- [ca|b] - 16
|
`- Time Out

Haskell parse error on input '|'

I'm getting the following error:
parse error on input '|'
with my code:
makeMove :: Player -> Board -> Maybe Board
makeMove p b | hasWinner b == Nothing = getMove p rb ri
where rb = gameTree p b
ri = minimax p rb
ros2int (i' :> ri') = i'
rb2b (b':rbs') = b
getMove p (r:rs) (i:is) = let bs = map rb2b rs
is = map ros2int is
idx = elemIndex (maximum' is) is
res (Nothing) = Nothing
res (Just x) = Just ((bs)!!x)
in res idx
| otherwise = Nothing
However I suppose this would be caused by tabs interference usually but I checked and I only used spaces so that couldn't be the problem. Could anyone help me out on this?
Thanks in advance!
Best regards,
Skyfe.
The where clause should be after all guards:
fun a b
| one = ...
| oterwise = ...
where ....

'where' inside other expression

I can use let inside other expression.
foo n = (let a = True in (\x -> a)) 3
foo' n | n == 1 = let a = True in a
| n /= 1 = False
But I can't do the same with where
foo n = ((\x -> a) where a = True) 3
foo' n | n == 1 = a where a = True
| n /= 1 = False
1:20: parse error on input `where'
Is it really impossible in haskell or just my mistake?
let is an expression while where is a clause. where is bound to syntactic constructs, let can be used anywhere expressions can.
You could of course write it like this:
foo n = ((\x -> a)) 3 where a = True
foo' n | n == 1 = a
| n /= 1 = False
where a = True
or like this:
foo n = (\a -> (\x -> a) 3) True
You need to put the where clause at the end:
foo n = ((\x -> a)) 3
where a = True
foo' n | n == 1 = a
| n /= 1 = False
where a = True
The difference is that let is an expression, whereas where requires some other construct to be bound to. See let vs where
let ... in ... is for introducing name bindings in an expression.
where is convenience syntax for giving local auxiliary definitions along with an equation. You can only use it as part of an equation (at the end), not in the middle of an arbitrary expression.
Their usage is not the same.
The claim that let is an expression is a bit off, it seems to me; in a do block it is a statement, though we say that there it abbreviates let ... in. The thing to say, I think, is
let_in_ :: Statement -> Expression -> Expression
_where_ :: Statement -> Statement -> Statement
Thus the first part of a let is a statement and can be modified by a where. So for example
foo n = (let a = b where b = True in (\x -> a)) 3
bip = do
let a = b where b = let c = d where d = True in c
return a
Similarly we can maybe say something like this:
case_of_ :: Expression -> [Statement] -> Expression
so that e.g.
z x = case even x of
True -> d where d = x + 1
False -> w - 1 where w = let a = x in a + 1

Resources