我正在为我们得到的一项任务而苦苦挣扎。我在这里根据不同的指南稍微编写了这段代码:不在范围内:数据构造函数
我遇到的问题是这里的管道:
| x == "+" = (Sum y y',xs'') where
这个问题似乎与在“where”后面有 3 个管道或一个管道有关。如果我交换最后 2 个管道。推杆
x == "+" = (Sum y y' (...))
前
x == "*" = (Prod y y' (...))
导致错误移动到该代码。如果我注释掉这两个代码段中的任何一个,一切正常,但我需要它们两个来完成我们被分配的任务。
快速总结:
| 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'
两者都 100% 单独工作,但是当我将它们放在一起时,我的程序无法编译。
完整代码:
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'