gpt4 book ai didi

haskell - Haskell 中如何解析撇号/字 rune 字?

转载 作者:行者123 更新时间:2023-12-02 13:28:06 29 4
gpt4 key购买 nike

我正在尝试编写一些读取 Lambda 表达式并输出 beta 缩减版本的东西。 Lambda 的类型如下:\variable -> expression,应用程序的形式为 (表达式) (表达式)。因此,如果在字符串开头找到“\”,它就知道要处理 Lambda,如果找到“(”,它就知道要处理应用程序。

我定义了 Lambda 表达式的类型:

data Expression = Variable String
| Lambda Expression Expression
| Apply Expression Expression

这是我第一次尝试编写一个读取输入的函数

processInput :: String -> Expression
processInput ('\':input) = processLambda input
processInput ('(':input) = processApply input
processInput str = Variable str

当我尝试加载这个函数时,我得到了

lexical error in string/character literal at ':'

所以我尝试使用守卫来代替:

processInput input
| head input == '\' = processLambda (tail input)
| head input == '(' = processApply (tail input)
| otherwise = Variable input

但是得到了

lexical error in string/character literal at character ' '

我不知道这两个函数有什么问题。

最佳答案

反斜杠是字符串和字 rune 本中的特殊字符。您可以用来表示不可打印的字符、换行符以及在文字中具有特殊含义的字符。例如 '\n' 是换行符 '\b' 是退格,'\'' 是单引号(不带\,第二个 ' 将被视为字 rune 字的结尾)。

因此,当您编写 '\' 时,词法分析器会看到字 rune 字的开头,后跟转义的 '。现在它期望另一个 ' 来关闭字 rune 字,但得到一个冒号,从而导致错误。

要将反斜杠表示为字 rune 字,可以使用另一个反斜杠转义反斜杠,如下所示:'\\'

关于haskell - Haskell 中如何解析撇号/字 rune 字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742789/

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