代码之家  ›  专栏  ›  技术社区  ›  Eben Kadile

在Haskell中如何解析撇号/字符文字?

  •  2
  • Eben Kadile  · 技术社区  · 7 年前

    我定义了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 ' '
    

    2 回复  |  直到 7 年前
        1
  •  6
  •   sepp2k    7 年前

    反斜杠是字符串和字符文字中的特殊字符。用于表示不可打印的字符、换行符和在文字中具有特殊含义的字符。例如 '\n' 是换行符 '\b' '\'' 是一个单引号(没有 \ ,第二个“将被视为字符文字的结尾)。

    所以当你写作的时候 '\' ' . 现在它期待着另一个 以关闭字符文字,但取而代之的是冒号,从而导致错误。

    要将反斜杠表示为字符文字,请使用以下另一个反斜杠转义反斜杠: '\\' .

        2
  •  2
  •   Chad Gilbert    7 年前

    '\\' .

    processInput ('\\':input) = processLambda input
    ...
    
    -- or...
    processInput input
        | head input == '\\'                      = processLambda (tail input)
    ...