要练习我的Haskell技能,请遵循Write Yourself a Scheme教程。我已经为s表达式实现了解析器,但是我在打印功能方面遇到了麻烦。
当我运行以下程序时
main :: IO ()
main = do args <- getArgs
putStrLn $ readExpr (args !! 0)
它正确地解析了s表达式,但是当我定义自己的shows
而不是deriving
时,我得到嵌套列表的错误输出和向量内的列表:
$ ./parser "(1 (2) 3)"
(1 (2 3))
$ ./parser "#(1 (2) 3)"
#(1 (2 3))
$ ./parser "(1 (2 (3)) 4)"
(1 (2 (3 4)))
$ ./parser "(1 (2 (3)) (4))"
(1 (2 (3 (4))))
其他情况和嵌套向量工作正常,但是:
lars@zygmunt:~/src/scm48$ ./parser "(1 #(2) 3)"
(1 #(2) 3)
lars@zygmunt:~/src/scm48$ ./parser "#(1 #(2) 3)"
#(1 #(2) 3)
lars@zygmunt:~/src/scm48$ ./parser "(1 (2 3))"
(1 (2 3))
我已将LispVal
的表示形式更改为包含Nil
和Pair
构造函数,而不是List
和DottedList
,因为它们与Scheme数据模型。打印列表由
showsVal :: Value -> ShowS
showsVal Nil = ("()" ++)
showsVal (Pair x y) = ("(" ++) . showsPair x y . (++ ")")
showsVal (String s) = shows s
showsVal (Symbol n) = (n ++)
showsVal (Number x) = shows x
showsVal (Boolean True) = ("#t" ++)
showsVal (Boolean False) = ("#f" ++)
showsVal (Vector v) = ("#(" ++) . showsVec v . (")" ++)
showsPair x Nil = showsVal x
showsPair x (Pair y z) = (showsVal x) . (" " ++) . showsPair y z
showsPair x y = (showsVal x) . (" . " ++) . (showsVal y)
showsVec [] = id
showsVec [x] = shows x
showsVec (x:xs) = shows x . (" " ++) . showsVec xs
我怀疑错误发生在showsPair
,但我无法弄清楚。
答案 0 :(得分:3)
我发现了自己:
showsVal (Pair x y) = ("(" ++) . showsPair x y . (++ ")")
应该是
showsVal (Pair x y) = ("(" ++) . showsPair x y . (")" ++)
-- ^^^^^^