Hacker News new | ask | show | jobs
by Twisol 1869 days ago
> I wonder why auto-curried function syntax has become so ubiquitous in explaining this.

I think it's primarily because this is the form you use them in in a language like Haskell. Most explanations are exported from Haskell in one way or another, so they're deeply colored by Haskellisms.

It's the same reason why `ap` and `bind` are generally preferred over `times` and `join` -- in Haskell you can even use `f <$> a <*> b`, which is a deeply clever use of infix `fmap` and `ap` that drives a syntactic analogy with regular function application, `f a b`. Try doing that in another language and you'll barf. And do-notation desugars most cleanly into >>=, so that's where Haskell-oriented explanations start from.

If you implement these in Java (which you can, you just can't abstract over T), it looks like this:

    class List<A> {
      <B> List<A> map(Function<A, B> f) { ... }
      
      <B, C> List<C> map2(List<B> other, BiFunction<A, B, C> f) { ... }

      <B> List<B> flatMap(Function<A, List<B>> f) { ... }

      // bonus; note that these make more sense static
      static <A, B> List<Pair<A, B>> times(List<A> as, List<B> bs) { ... }

      // in fact, this one has to be static
      static <A> List<A> join(List<List<A>> aas) { ... }
    }
That is, the second argument `T a` in the top poster's comment becomes the implicit `this` parameter for instance methods. I find the `static` alternatives often make more syntactic sense in context; just goes to show that one language's norms don't always transfer.
2 comments

You can also look at the Scala implementations if you like. Scala has HKTs so you can write it all directly.

   trait Functor[F[_]] {
     def map[A, B](f: A => B)(x: F[A]): F[B]
   }

   trait Applicative[F[_]] extends Functor[F] {
     def pure[A](a: A): F[A]
     def apply[A, B](f: F[A => B])(x: F[A]): F[B]
     def product[A, B](xa: F[A], xb: F[B]): F[(A, B)]
   }

   trait Monad[F[_]] extends Applicative[F] {
     def bind[A, B](f: A => F[B])(x: F[A]): F[B]
     def join[A](x: F[F[A]]): F[A]
   }
That version is extremely noisy, imo.
I once had to add logging to a large set of methods in C#, so I thought, well, let's make a function decorator like Python or Haskell, there's no reason it wouldn't work on C#.

Well, it indeed worked perfectly well. But the amount of noise added to satisfy the type checker was larger than reimplementing the log procedure at each place.

The version in Java? Yes, because it's Java.