简体   繁体   中英

Does Scala have an operator similar to Haskell's `$`?

Does Scala have an operator similar to Haskell's $ ?

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

Yes, it's written "apply"

fn apply arg

There's no standard punctuation operator for this, but it would be easy enough to add one via library pimping.

  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)

In general, while Scala code is much denser than Java, it's not quite as dense as Haskell. Thus, there's less payoff to creating operators like '$' and '.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM