gpt4 book ai didi

haskell - 尝试在 Haskell 中构建词法分析程序

转载 作者:行者123 更新时间:2023-12-04 11:00:18 25 4
gpt4 key购买 nike

我正在开始这个项目,但进展甚微。我刚开始使用haskell,所以我只想使用我实现的功能,以便我将大脑付诸行动。

我想要两个字符串列表,一个代表代码,另一个为给定的语言保留名称。我希望能够从第一个列表中过滤所说的单词。


resNames = ["function","while","for","const","let","this","true","false",";","=", "()", "var"]

findVal :: [String]->String->[String]
findVal z " " = z
findVal [] value = []
findVal (x:y) value = if x == value then findVal y value
else x:(findVal y value)

filterResNames :: [String]->[String]->[String]
filterResNames z [] = z
filterResNames [] z = []
filterResNames (x:y) (u:v) = if x== u then findVal (x:y) (u) else x:(filterResNames y (u:v))```

This obviously doesn't work because the program stops as soon as it finds a match...

最佳答案

如果我正确解释您的想法,这可能是一个可能的解决方案:

resNames = ["function","while","for","const","let","this","true","false",";","=", "()", "var"]

-- Determine whether an element is in a list
findVal :: String->[String]->Bool
findVal _ [] = False
findVal x (namesH:namesT) =
if x == namesH
then True
else (findVal x namesT)

-- Loop over input list and for each element, if not in reserved list, add to accumulator
filterResNamesAcc :: [String]->[String]->[String]->[String]
filterResNamesAcc _ [] acc = acc
filterResNamesAcc [] _ acc = acc
filterResNamesAcc (inH:inT) names acc =
if (findVal inH names)
then (filterResNamesAcc inT names acc)
else (filterResNamesAcc inT names (inH:acc))

-- Invoke filterResNamesAcc with empty accumulator
filterResNames :: [String]->[String]->[String]
filterResNames inL names = reverse (filterResNamesAcc inL names [])

main = do
print (filterResNames ["hello", "for", "the", "world"] resNames)

我们在这里使用的是函数式语言中使用的典型累加器模式。 filterResNamesAcc 的“问题”是使用 :前置到累加器会导致结果反转,因此调用 reverse .

留给“读者”:
  • 实现自己的反向或找出不需要它的更复杂的折叠模式。
  • 更改 filterResNames 的签名取一个字符串并进行标记化。
  • 关于haskell - 尝试在 Haskell 中构建词法分析程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848618/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com