【问题标题】:Apostrophe in identifiers in HaskellHaskell 标识符中的撇号
【发布时间】:2011-04-15 07:58:41
【问题描述】:

我在网上找到了这段代码:

digits 0 = [0]
digits n = digits' n []
  where digits' 0 ds = ds
        digits' n ds = let (q,r) = quotRem n 10
                       in digits' q (r:ds)

sumOfDigits = sum . digits

有人可以快速解释递归函数调用后的“'”符号(digits n = digits' n [])的用途吗?我在 Haskell(教程)中看到了一些其他代码示例,但我不明白这个。快速解释表示赞赏。

【问题讨论】:

  • 我个人尽量避免在标识符中使用撇号,因为我非常喜欢描述性和有意义的短语。

标签: haskell coding-style identifier


【解决方案1】:

撇号只是名称的一部分。它是 Haskell 中采用的命名约定(习语)。

Haskell 中的约定是,like in math,变量名称上的撇号表示与先前变量有某种关联或相似的变量。

一个例子:

let x  = 1
    x' = x * 2
in x'

x'x 相关,我们用撇号表示。


顺便说一句,你可以在 GHCi 中运行它,

Prelude> :{ 
Prelude| let x  = 1
Prelude|     x' = x * 2
Prelude| in x'
Prelude| :}
2

【讨论】:

  • 您的示例不起作用。既不在 .hs 文件中,也不直接写入解释器。
  • @user504060:试试let { x = 1; x' = x * 2 } in x'。 (多行结构不像在 ghci 中那样工作,并且表达式不在 Haskell 源文件的顶层。)
  • 这是一个 Haskell 表达式。我已经编辑了答案,以展示如何在 GHCi 中评估多行表达式。
  • +1 用于展示如何在 ghci 中使用布局。我不知道。
【解决方案2】:

这只是标识符中允许的另一个字符。把它想象成另一个字母。

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多