是否可以在实例子句中使用`let in`?

时间:2019-03-11 16:03:27

标签: haskell compiler-errors syntax-error

import Prelude hiding (Either (..))

data Tree a = Empty | Node a (Tree a) (Tree a)

instance Show a => Show (Tree a) where
  show t = show ST t

data ShowableTree a = ST Int (Tree a)

instance Show a => Show (ShowableTree a) where
  let
    indent 0 = ""
    indent n = "\t" ++ (indent n-1)
  in
    show (ST depth Empty) = (indent depth) ++ "()"
    show (ST depth (Node n l r)) =
      let
        stl = ST (depth+1) l
        str = ST (depth+1) r
      in
        (indent depth) ++ "(\n" ++ (indent depth) ++ (show n) ++ "\n" ++ (show stl) ++ "\n" ++ (show str) ++ "\n" ++ (indent depth) ++ ")\n"

这会吐出错误:

[m@green09 ~]$ ghci labn.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( labn.hs, interpreted )

labn.hs:14:3:
    parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.

也许我们尝试where吗?

instance Show a => Show (ShowableTree a)
  where
    show (ST depth Empty) = (indent depth) ++ "()"
    show (ST depth (Node n l r)) =
      let
        stl = ST (depth+1) l
        str = ST (depth+1) r
      in
        (indent depth) ++ "(\n" ++ (indent depth) ++ (show n) ++ "\n" ++ (show stl) ++ "\n" ++ (show str) ++ "\n" ++ (indent depth) ++ ")\n"
    where
      indent 0 = ""
      indent n = "\t" ++ (indent n-1)

仍然没有成功:

[m@green09 ~]$ ghci labn.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( labn.hs, interpreted )

labn.hs:19:5: parse error on input `where'
Failed, modules loaded: none.

一个明确的解决方案是通过将indent的定义移至全局范围来污染全局范围。

但是,是否可以在indent内以某种方式定义ShowableTree

0 个答案:

没有答案