Parsing S Expression

陌路散爱 提交于 2019-12-08 07:57:53

问题


Given the following definitions that make up an S Expression from Prof. Yorgey's course:

data Atom = N Integer | I Ident deriving Show

and

data SExpr = A Atom | Comb [SExpr] deriving Show

What should the full data type be (in Haskell) for the following?

(bar (foo) 3 5 874)


回答1:


I believe it would be something like

Comb
    [ A (I "bar")
    , Comb
        [ A (I "foo")
        ]
    , A (N 3)
    , A (N 5)
    , A (N 874)
    ]

Whenever you encounter an open parenthesis you would start a new Comb expression, so (foo) is Comb [A (I "foo")] while foo is simply A (I "foo").




回答2:


I'll assume the Ident type is a String.

  • bar as an Atom is I "bar", and as an SExpr is A (I "bar")
  • ditto for foo
  • (foo) is an SExpr and is constructed as Comb [ A (I "foo") ]
  • 3 as an Atom is N 3 and as an SExpr is A (N 3)
  • ditto for 5 and 874
  • the complete construction of (bar (foo) 3 5 874) (which is an SExpr) is

.

Comb [ A (I "bar")
     , Comb [ A (I "foo") ]
     , A (N 3)
     , A (N 5)
     , A (N 874)
     ]


来源:https://stackoverflow.com/questions/27894888/parsing-s-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!