TemplateHaskell 未安装...然后是

Inf*_*uts 1 haskell template-haskell

我正在用 Haskell 编写一个程序,它涉及很多括号。因此,为了清理那一团丑陋的混乱,我使用了$几次运算符来使其更易于阅读。例如:

longFunc arg1 (anotherFunc (yetAnotherFunc arg2))
Run Code Online (Sandbox Code Playgroud)

被替换为

longFunc arg1 $ anotherFunc $ yetAnotherFunc arg2
Run Code Online (Sandbox Code Playgroud)

但是当我使用 GHCi 编译我的程序时,我收到一条消息:

MyFile.hs:18:18: error:
    parse error on input ‘$’
    Perhaps you intended to use TemplateHaskell
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

这是第 16-18 行:

MyFile.hs:18:18: error:
    parse error on input ‘$’
    Perhaps you intended to use TemplateHaskell
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

我很困惑,因为我已经多次使用该$运算符(使用相同的编译器),如下所示:

isDigit :: Char -> Bool
isDigit c =
  c `elem` $ ['0'..'9'] ++ "."
Run Code Online (Sandbox Code Playgroud)

所以我将该代码作为测试输入到我的文件中,删除了其他$出现的内容,然后加载了它。

它奏效了!

有人可以告诉我这是怎么回事吗?

And*_*Ray 7

您不能($)在另一个中缀运算符之后立即使用。第 18 行:

c `elem` $ ['0'..'9'] ++ "."
Run Code Online (Sandbox Code Playgroud)

需要重写为以下选项之一:

  1. 保持括号原样:

    c `elem` (['0'..'9'] ++ "."])
    
    Run Code Online (Sandbox Code Playgroud)
  2. 适用($)于以下切片elem

    (c `elem`) $ ['0'..'9'] ++ "."
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将调用转换elem为前缀调用:

    elem c $ ['0'..'9'] ++ "."
    
    Run Code Online (Sandbox Code Playgroud)

我推荐选项 3。连续的中缀运算符(在本例中为`elem`$)没有明确定义的优先级并且会混淆解析器。一般的经验法则是中缀运算符的每一侧必须始终具有完整的表达式。c `elem`不是完整的表达式,因此不允许出现在$. 同样,$ ['0'..'9'] ++ "."不是完整的表达式,所以不允许在 的右边`elem`