假设我的haskell代码中定义了以下数据结构
data Exp = Expnum Int - constant
| Expplus Exp Exp - addition
从技术上讲,这个表达式可以有无限多个项。如果我想提取它的术语,我该怎么做?(我想不出办法,因为我不知道如何处理Haskell中的无限多个参数(
例如:
-- Example: (Expplus (Expplus (Expplus (Expnum 1) (Expnum 2)) (Expnum 3)) (Expnum 4))
extract :: Exp -> [Int]
... -- Not sure how to deal with infinite number of Expnum :(
-- Expected output [1,2,3,4]
您可以构建一个列表,其中每个"叶子;会在尾部做准备,所以类似于:
helper :: Exp -> [Int] -> [Int]
helper (Expnum i) = (i:)
helper (Expplus sa sb) =helpersa .helpersb
现在我们可以使用该助手来制作一个完整的列表,我将其作为练习。