Haskell 中函数名末尾的 'mean/do 是什么意思?
What does ' mean/do at the end of function name in Haskell?
几天前我从Haskell开始,我在网上找到了一些解决我问题的方法,但我开始注意到有些函数在函数名的末尾有一个符号。
什么意思?
一个例子可以是
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = foldr (\y ys -> (f y):ys) [] xs
Source
通常添加 '
以表示这是函数 map
的某些 变体 。它实际上只是名称的一部分(它是一个有效字符)。
在此示例中,map
已由 Prelude
提供,因此您会遇到名称冲突。所以需要一个不同的名字,map'
不用想太多就可以完成这项工作。
通常'
表示函数也是strict(例如foldl'
)。
字符'
可以加在Haskell中的任意标识符,所以map'
是一个标识符。在这种情况下,'
is also called "prime",因此如果您大声朗读,map'
将发音为“map prime”。
这种用法源于数学,其中函数变体(通常是它们的导数)附有某种符号,例如
Function
Meaning
f
Original function
f'
Derivative of f
f''
Second derivative f
f*
Some special variant of f (usually called "f star")
f̂ (f with ^)
Some other special variant, usually the Fourier transform of f, called "f hat".
在Haskell中,素数通常表示a
- 严格变体(例如
foldl'
),
- 自定义实现(例如
map'
在您自己的代码中,因为它与 Prelude.map
冲突),
- 从另一个派生的值(例如
x' = go x
)或
- 内部函数(库中的实现细节)
特别是第三个变体经常出现在 where
或 let
从句中。命名毕竟很难,单个素数既可以显示值的来源,又无需想出更好的名称:
-- | '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开始,我在网上找到了一些解决我问题的方法,但我开始注意到有些函数在函数名的末尾有一个符号。
什么意思?
一个例子可以是
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = foldr (\y ys -> (f y):ys) [] xs
Source
通常添加 '
以表示这是函数 map
的某些 变体 。它实际上只是名称的一部分(它是一个有效字符)。
在此示例中,map
已由 Prelude
提供,因此您会遇到名称冲突。所以需要一个不同的名字,map'
不用想太多就可以完成这项工作。
通常'
表示函数也是strict(例如foldl'
)。
字符'
可以加在Haskell中的任意标识符,所以map'
是一个标识符。在这种情况下,'
is also called "prime",因此如果您大声朗读,map'
将发音为“map prime”。
这种用法源于数学,其中函数变体(通常是它们的导数)附有某种符号,例如
Function | Meaning |
---|---|
f | Original function |
f' | Derivative of f |
f'' | Second derivative f |
f* | Some special variant of f (usually called "f star") |
f̂ (f with ^) | Some other special variant, usually the Fourier transform of f, called "f hat". |
在Haskell中,素数通常表示a
- 严格变体(例如
foldl'
), - 自定义实现(例如
map'
在您自己的代码中,因为它与Prelude.map
冲突), - 从另一个派生的值(例如
x' = go x
)或 - 内部函数(库中的实现细节)
特别是第三个变体经常出现在 where
或 let
从句中。命名毕竟很难,单个素数既可以显示值的来源,又无需想出更好的名称:
-- | '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
冲突。