haskell - s-expr 打印功能中的错误

标签 haskell lisp scheme s-expression

为了练习我的 Haskell 技能,我遵循 Write Yourself a Scheme教程。我已经实现了 s 表达式的解析器,但在打印功能方面遇到了问题。

当我运行以下程序时

main :: IO ()
main  =  do args <- getArgs
            putStrLn $ readExpr (args !! 0)

它正确解析 s 表达式,但是当我定义自己的 shows 而不是派生它时,我会得到嵌套列表和向量内列表的错误输出:

$ ./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 的表示形式,以包含 NilPair 构造函数,而不是 ListDottedList,因为它们与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 中,但我就是无法弄清楚。

最佳答案

我自己发现:

showsVal (Pair x y)  =  ("(" ++) . showsPair x y . (++ ")")

应该是

showsVal (Pair x y)  =  ("(" ++) . showsPair x y . (")" ++)
                                                --  ^^^^^^

关于haskell - s-expr 打印功能中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5261213/

相关文章:

haskell - State Monad,随机数序列和monadic码

haskell - 表示红黑树的最有效方法是什么?

emacs - 是什么让您想学习 Common Lisp?你想从中得到什么?

scheme - 如何在方案中生成 lambda 列表?

lisp - Scheme,N-queens 优化策略 SICP 第 2 章

haskell - 为什么在尝试映射列表列表时会出现此错误?

parsing - Applicative Functor 中的条件循环

lisp - 如何避免在 Common Lisp 中完成脚本?

scheme - 是否可以根据要比较的数据生成相等函数?

algorithm - 方案功能