kolchanov
kolchanov

Reputation: 2088

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

Upvotes: 12

Views: 1574

Answers (1)

Dave Griffith
Dave Griffith

Reputation: 20515

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

Upvotes: 18

Related Questions