Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Re "Advanced Mistake #4", do Javascript programmers not know about tuples? Does nobody write functions with signatures like

    pair(pa: Promise<A>, pb: (a: A) => Promise<B>): Promise<{fst: A, snd: B}> {
      
      return pa.then(function (a) { 
        return pb(a).map(function (b) {
          return {fst: a, snd: b}
        })
      })

    }
It's a super reusable little chunk of code.


It is, but it only works for pairs and then you wind up with the relatively nonsensical 'fst' and 'snd' names.

My preference would be:

  let user = await getUserByName('nolan');
  let userAccount = await getUserAccountById(user.id);
  // stuff with user and userAccount
But I have long since decided that I am never writing ES5 again, and since I therefore need Babel anyways I may as well turn 'stage: 1' on and use async/await. It's basically do-notation for promises.


So alpha convert your names to whatever you like. I don't know how to do it namelessly in Javascript without Chuch encoding the pair.

You can go much further than this. The following operation

    ap<A, B>(pf: Promise<(a: A) => B>): (pa: Promise<A>) => Promise<B> {
      return (pa: Promise<A>) =>
        pf.then((f) => pa.then((a) => Promise.resolve(f(a))))
    }
can be used to extend the previous idea as far as you like.


I'm having trouble grokking whatever type-added syntax you're using for Javascript here. I'm guessing it's:

  function ap(pf) {
    return (pa) =>
      pf.then((f) => pa.then((a) => Promise.resolve(f(a))))
  }
Still, if I wanted to go full-hog static-typed functional I doubt I'd be using straight Javascript, I'd probably try one of the various Haskell-alike to JS converters. Promises with async/await syntax seems like the most practical of the various solutions whilst still feeling like Javascript.

(Besides, I prefer dynamic typing and I find points-free style in Haskell to be obfuscating rather than clarifying, so it seems unlikely we're going to have the same opinion of the best way to accomplish things here. :)


Sorry, I'm just writing in Typescript. It's the typed Javascript flavor I'm most familiar with. But, yep, you properly erased the types.

I'd love to use Haskell-to-JS but I don't think I could bet a product on it quite yet.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: