I am struggeling with an assignment we have been given. I have written this code slightly based on a different guide here: Not in scope: data constructor
The problem i have is a the pipe here:
| x == "+" = (Sum y y',xs'') where
The problem seems to be related to having 3 pipes or a pipe following a “where”. If i swap the 2 last pipes.
Putting
x == "+" = (Sum y y' (...))
before
x == "*" = (Prod y y' (...))
causes the error to move to that code. If i comment out any one of these two code segments everything works fine, but i need both of them for the assignment we have been given.
Quick summary:
| x == "*" = (Prod y y',xs'') where
(y,xs') = ast xs
(y',xs'') = ast xs'
and
| x == "+" = (Sum y y',xs'') where
(y,xs') = ast xs
(y',xs'') = ast xs'
both work 100% alone, but when i put them together my program does not compile.
Full code:
import Data.Char
data AST = Leaf Int
| Sum AST AST
| Min AST
| Prod AST AST
deriving Show
tokenize::String -> [String]
tokenize[] = []
tokenize('+':xs) = "+": tokenize xs
tokenize('-':xs) = "-": tokenize xs
tokenize('*':xs) = "*": tokenize xs
tokenize(x:xs) = if isDigit x then (takeWhile isDigit (x:xs)) : tokenize (dropWhile isDigit xs) else tokenize(xs)
ast :: [String] -> (AST,[String])
ast [] = error "Empty string"
ast (x:xs) | all isDigit x = (Leaf (read x),xs)
| x == "-" = let (y,xs') = ast xs in (Min y,xs')
| x == "*" = (Prod y y',xs'') where
(y,xs') = ast xs
(y',xs'') = ast xs'
| x == "+" = (Sum y y',xs'') where
(y,xs') = ast xs
(y',xs'') = ast xs'
The problem in
is that you can have only one
whereclause per equation in the function definition. So after thewherein thex == "*"alternative, the parser expects the equation for the pattern(x:xs)to be complete.Just remove the offending
where, thewhereclause is scoped over all the alternatives in the equation, and bothwhereclauses have the same contents (and indent it nicer, thewherebelongs on its own line according to my preferences). Since theletin the first alternative uses a binding also present in thewhereclause, that can also be removed: