问题
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 isA (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 isA (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