'在Haskell中函数名称的末尾是什么意思/做什么?

几天前我开始使用 Haskell,我在网上找到了一些解决我的问题的方法,但我开始注意到某些函数在函数名的末尾有一个符号。

什么意思?

一个例子可能是

map'            :: (a -> b) -> [a] -> [b]
map' f []       = []
map' f (x:xs)   = foldr (y ys -> (f y):ys) [] xs

来源

回答

'通常加入表明这是一些变种的函数map。它实际上只是名称的一部分(它是一个有效字符)。

在这个例子中,这里map已经提供了,Prelude所以你会遇到名称冲突。所以需要一个不同的名字,map'不用考虑太多就可以完成工作。

通常'表示该函数也是严格的(例如foldl')。

  • it's not a stupid question at all - some students associate this with some kind of derivative (especially students having a math background 😉 ) - and most other languages don't allow the character for their identifiers so the confusion is very understandable
  • Thanks, so I can call this function as `map'`. thanks and sorry for the stupid question

回答

字符'可以添加到 Haskell 中的任何标识符,标识符也是如此map'。在这种情况下,'也称为"prime",因此map'如果您要大声朗读它,则会发音为 "map prime"。

使用源于数学,其中函数变体(通常是它们的导数)附有某种符号,例如

功能 意义
F 原创功能
F' f 的导数
F'' 二阶导数f
F* f 的一些特殊变体(通常称为“f star”
F?(f 带 ^) 其他一些特殊的变体,通常是f的傅立叶变换,称为“f hat”

在 Haskell 中,素数通常表示

  • 严格的变体(例如foldl'),
  • 自定义实现(例如map'在您自己的代码中,因为它与 冲突Prelude.map),
  • 从另一个值派生的值(例如x' = go x)或
  • 内部函数(库内的实现细节)

特别是第三个变体经常出现在whereorlet子句中。毕竟命名很难,一个素数可以让你既显示值的来源,又不需要想出更好的名字:

-- | 'pow x n' calculates 'x' to the power of 'n'. 
--    It uses the double-and-add method internally
pow :: Int -> Int -> Int
pow x 0 = 1
pow x 1 = x
pow x n
  | even n    = x' * x'      -- usage of 'pow x (n/2)' here
  | otherwise = x' * x' * x  -- use of both x' and x
 where   
   x'    = pow x (n `div` 2) -- x' stems from the original x

请注意,您'的标识符中可能有任意多个:

some'strange'example'don't'do'this :: Int
some'strange'example'don't'do'this = 12

foo'''''''''''''' = "please don't do this :)"

不允许在标识符开头使用单引号,因为它会与通常的 发生冲突Char


以上是'在Haskell中函数名称的末尾是什么意思/做什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>