Parse error in pattern: receiveTab - haskell

I have been working on a Haskell project. After producing some lines of code, and when I tried to load the .hs file via ghci, I receive this message, which I do not seem to understand why does it even show.
type Tab = [String]
task :: Tab -> Tab
task t =
let (receiveTab t) = a
(receivePosition t) = b --receivePosition and nextPosition are not really relevant to the context of this question
in nextPosition a b
receiveTab :: Tab -> Tab
receiveTab (h:t)
| elem ' ' h = []
| otherwise = receiveTab t
After attempting to load my .hs file, I receive the message:
task2.hs: Parse error in pattern: receiveTab
It might be a really simple mistake, but my brain can't process what's wrong there, and I can't really afford to just discard the code and start it all over again.

Did you perhaps mean
let a = receiveTab t
b = receivePosition t
Variables (or patterns in general) generally go to the left of the equals sign, values go to the right, as in most other languages.

Related

Generator in Haskell list comprehension not working

I am trying to generate a list which will contain a list of solutions for the problem I am trying to solve. I am doing this using list comprehension, generating all possible combinations and then using a predicate to filter so that only solutions are included. Here is my code.
solveRow :: Row -> [Row]
solveRow (Row target rowCells) =
[(cellsToRow target cls) | (cls <- (cellPermutations rowCells)), (result cls)==target]
cellPermutations returns [[Cell]] and therefore cls should be of type [Cell]. When I try to compile I get an error.
I thought <- passed each element of right hand side (in this case [Cell]) to the left hand side variable. Why am I getting a parse error for <-?
Don’t put brackets around cls <- (cellPermutations rowCells) — that’s a syntax error. You don’t need brackets around cellsToRow target cls either, although doing so isn’t an error. (And strictly speaking, you don’t need brackets around result cls either, but I personally think that those brackets make it more readable.) So your example should be:
solveRow :: Row -> [Row]
solveRow (Row target rowCells) =
[cellsToRow target cls | cls <- (cellPermutations rowCells), (result cls)==target]

Error message generating for every input for an empty list case

I'm doing my second assignment in my first semester of learning coding using haskell, so I'm quite new to coding. My problem is that every input I test, empty or not, generates my error message for the empty case, why would this be?
Type classes added for clarity. This is also part of an assignment so please only guide me for this one error :')
type Histogram a = Map a Int
inc :: Ord a => Histogram a -> a -> Histogram a
create
:: Ord a
=> Histogram a -> [a] -> Histogram a
create h (head:restOfString) = create (inc h head) restOfString
create h [head] = inc h head
create h [] = error "No elements in string"
This is wrong:
create h (head:restOfString) = ...
create h [head] = ...
when passing a list containing only one element, the first branch matches, with restOfString being empty. Hence, the second branch will never be taken.
Put the second line first.
If you turn on warnings with -Wall, GHC warns about many potential problems, including this one. I recommend it.
Your first two patterns overlap, so the first one always takes precedence over the second one. Swap them.
This triggers a warning by default in GHC, remember to read the compiler's output. For a better coding experience, it is also advisable to enable -Wall.

Error parsing case expression

I am getting this compile error:
Files.hs:47:17: parse error on input ‘->’
Failed, modules loaded: none.
In the following section of code:
main :: IO ()
main = do
args <- getArgs
let f = case args of
("W":_) -> eoltoW
-- ^ here's 47:17
("U":_) -> eoltoU
_ -> fail "2 - 3 arguments required"
case args of
[_,i,o] -> editWith f i o
[_,i] -> catWith f i
[_] -> fail "2 - 3 arguments required"
While I understand the logic could use some tidying up, I do not see where I am going wrong with case syntax. I figure it might be some weird interaction with do and let, but I can't find any clue as to how to correct it.
Note, I have ensured that I only use spaces for indentation
Edit:
It seems that adding a single space further of indentation (as below) is sufficient to prevent the error, but I am unclear as to why.
main = do
args <- getArgs
let f = case args of
("W":_) -> eoltoW
-- ^ here's 47:17
("U":_) -> eoltoU
_ -> fail "2 - 3 arguments required"
This is described in 2.7 and 10.3. Basically, the rule for let … in a do block* is that all bindings have to be indented the same way:
let a = …
b = …
c = …
Furthermore, the "…" have to be more indented than the layout list. For example, the following is a syntax error:
let a =
10
in a
In order to create a new layout-list, we need to indent it further (see note 1 in section 10.3), which is why
let a =
10
in a
is completely fine. The same holds for your case. All of the cases have to be further indented than f due to the off-side rule.
* that rule actually holds** for more, i.e. for let, where, do and of.
** well, as long as you don't introduce additional braces

Haskell: Need Enlightenment with Calculator program

I have an assignment which is to create a calculator program in Haskell. For example, users will be able to use the calculator by command lines like:
>var cola =5; //define a random variable
>cola*2+1;
(print 11)
>var pepsi = 10
>coca > pepsi;
(print false)
>def coke(x,y) = x+y; //define a random function
>coke(cola,pepsi);
(print 15)
//and actually it's more complicated than above
I have no clue how to program this in Haskell. All I can think of right now is to read the command line as a String, parse it into an array of tokens. Maybe go through the array, detect keywords such "var", "def" then call functions var, def which store variables/functions in a List or something like that. But then how do I store data so that I can use them later in my computation?
Also am I on the right track because I am actually very confused what to do next? :(
*In addition, I am not allowed to use Parsec!*
It looks like you have two distinct kinds of input: declarations (creating new variables and functions) and expressions (calculating things).
You should first define some data structures so you can work out what sort of things you are going to be dealing with. Something like:
data Command = Define Definition | Calculate Expression | Quit
type Name = String
data Definition = DefVar Name Expression | DefFunc Name [Name] Expression
-- ^ alternatively, implement variables as zero-argument functions
-- and merge these cases
data Expression = Var Name | Add Expression Expression | -- ... other stuff
type Environment = [Definition]
To start off with, just parse (tokenise and then parse the tokens, perhaps) the stuff into a Command, and then decide what to do with it.
Expressions are comparatively easy. You assume you already have all the definitions you need (an Environment) and then just look up any variables or do additions or whatever.
Definitions are a bit trickier. Once you've decided what new definition to make, you need to add it to the environment. How exactly you do this depends on how exactly you iterate through the lines, but you'll need to pass the new environment back from the interpreter to the thing which fetches the next line and runs the interpreter on it. Something like:
main :: IO ()
main = mainLoop emptyEnv
where
emptyEnv = []
mainLoop :: Environment -> IO ()
mainLoop env = do
str <- getLine
case parseCommnad str of
Nothing -> do
putStrLn "parse failed!"
mainLoop env
Just Quit -> do
return ()
Just (Define d) -> do
mainLoop (d : env)
Just (Calculate e) -> do
putStrLn (calc env e)
mainLoop env
-- the real meat:
parseCommand :: String -> Maybe Command
calc :: Environment -> Expression -> String -- or Integer or some other appropriate type
calc will need to look stuff up in the environment you create as you go along, so you'll probably also need a function for finding which Definition corresponds to a given Name (or complaining that there isn't one).
Some other decisions you should make:
What do I do when someone tries to redefine a variable?
What if I used one of those variables in the definition of a function? Do I evaluate a function definition when it is created or when it is used?
These questions may affect the design of the above program, but I'll leave it up to you to work out how.
First, you can learn a lot from this tutorial for haskell programming
You need to write your function in another doc with .hs
And you can load the file from you compiler and use all the function you create
For example
plus :: Int -> Int -- that mean the function just work with a number of type int and return Int
plus x y = x + y -- they receive x and y and do the operation

Type Problems chaining CaseOf Statements with Parsec

I'm learning haskell, and my current project is writing a parser to read a text file representation of a database.
At the moment, I'm setting up the code for reading individual fields of tables. In the text file, fields look either like this:
name type flags format
or this:
name type format
This gives the trouble of having to account for cases of there being a flag or not being a flag. I solved this in my main function like this:
main = case parse fieldsWithFlags "(test)" testLine of
Left err -> noFlags
Right res -> print res
where noFlags = case parse fieldsWithoutFlags "(test)" testLine of
Left err -> print err
Right res -> print res
If I understand correctly, this says "If it's a line that doesn't have flags, try to parse it as such; otherwise, return an error." It prints the correct results for any "testLine" I throw at it, and returns errors if both options fail. However, when I try to pull this out into its own function, like this:
field :: Either ParseError Field
field = case parse fieldsWithFlags "(test)" testLine of
Left err -> noFlags
Right res -> return Right res
where noFlags = case parse fieldsWithoutFlags "(test)" testLine of
Left err -> return Left err
Right res -> return Right res
main = case field of
Left err -> print err
Right res -> print res
GHC gives me:
haskellParsing.hs:58:26:
Couldn't match expected type `Either ParseError Field'
with actual type `b0 -> Either b0 b0'
In the expression: noFlags
In a case alternative: Left err -> noFlags
In the expression:
case parse fieldsWithFlags "(test)" testLine of {
Left err -> noFlags
Right res -> return Right res }
I've played around with this a lot, but just can't get it working. I'm sure there's a much more clear-headed way of doing this, so any suggestions would be welcome - but I also want to understand why this isn't working.
Full code is at: http://pastebin.com/ajG6BkPU
Thanks!
You don't need the return in your cases. Once you wrap something in Left or Right it is in Either; since you only need a Either ParseError Field, the Left and Right do not need an extra return.
Also, you should be able to simplify your parseFields significantly. You can write a new parser that looks like this:
fields = try fieldsWithFlags <|> fieldsWithoutFlags
what this does is run the first one and, if it fails, backtrack and run the second one. The try is important because this is what enables the backtracking behavior. You have to backtrack because fieldsWithFlags consumes some of the input that you care about.
Now you should be able to just use fields in your main function.
Since the form without flags is almost identical to that with flags (just that the flags are missing), the alternative can be pushed down to where the flags might appear. In this way, you avoid backtracking over name and type in with-flags, just to parse them again in without-flags. We could combine the with and without fields parsers like this:
fields = do
iName <- getFieldName
spaces
iType <- getDataType
spaces
iFlag <- option "" $ try getFlag
spaces
iFormat <- getFormat
newline -- this was only present in without flags, was that intended?
return $ Field iName iType iFlag iFormat

Resources