Scala是否有类似于Haskell的"$"操作符?

12

Scala有没有类似于Haskell的$操作符?

-- | 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

11
为了使问题独立,如果您能解释一下Haskell的这个结构是什么/做什么,那就太好了。 - Randall Schulz
1
$ 显然是右结合的,且优先级较低。http://learnyouahaskell.com/higher-order-functions#function-application。 - huynhjl
1个回答

18

是的,它写着“应用”

fn apply arg

目前还没有针对此功能的标准标点运算符,但可以通过库扩展很容易地添加一个。

  class RichFunction[-A,+B](fn: Function1[A, B]){ def $(a:A):B = fn(a)}
  implicit def function2RichFunction[-A,+B](t: Function1[A, B]) = new RichFunction[A, B](t)

总体而言,虽然Scala代码比Java更加紧凑,但并不像Haskell那样紧凑。因此,创建像'$'和'.'这样的运算符收益较少。


8
$ 的一个较大优点是它在操作符部分中的使用: (f $)($ x),这在 Scala 中不存在(你需写成 f(_)_(x),但在 Haskell 中不能这样做)。 - Alexey Romanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接