Haskell:区别 . (点)和$(美元符号)点( . )和美元符号($)之间有什么区别?据我了解,它们都是不需要使用括号的语法糖 .
它们是 not 语法糖,不需要使用括号 - 它们是函数, - 无效,因此我们可以称它们为运算符 .
(.) 是撰写函数 . 所以
result = (f . g) x
与构建一个函数相同,该函数将传递给 g 的参数的结果传递给 f .
h = \x -> f (g x)
result = h x
($) 是具有低绑定优先级的右关联应用函数 . 所以它只是首先计算它右边的东西 . 从而,
result = f $ g x
在程序上是这样的(这很重要,因为Haskell被懒惰地评估,它将首先开始评估 f ):
h = f
g_x = g x
result = h g_x
或者更简洁:
result = f (g x)
我们可以通过阅读每个函数的源来看到这一点 .
阅读来源
这是source for (.) :
-- | Function composition.
{-# INLINE (.) #-}
-- Make sure it has TWO args only on the left, so that it inlines
-- when applied to two functions, even if there is no final argument
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
这是source为 ($) :
-- | Application operator. This operator is redundant, since ordinary
-- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- > f $ g $ h x = f (g (h x))
--
-- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
-- or @'Data.List.zipWith' ('$') fs xs@.
{-# INLINE ($) #-}
($) :: (a -> b) -> a -> b
f $ x = f x
何时使用:
当您不需要立即评估函数时使用合成 . 也许你想将由合成产生的函数传递给另一个函数 .
在提供完整评估的所有参数时使用应用程序 .
因此,对于我们的示例,它在语义上是可取的
f $ g x
当我们有 x (或更确切地说, g 的参数),并且:
f . g
当我们没有 .