mostly-adequate-guide icon indicating copy to clipboard operation
mostly-adequate-guide copied to clipboard

fix regression of IO.join in chapter 9

Open NANASHI0X74 opened this issue 3 years ago • 1 comments

I noticed today that the IO.join() method seemed off, so I searched in issues and PRs whether someone else had spoken about this, subsequently I found this PR: https://github.com/MostlyAdequate/mostly-adequate-guide/pull/265 which had fixed the issue and this commit: https://github.com/MostlyAdequate/mostly-adequate-guide/commit/f1608d399c4045c0fe2b18824464c91e3afe9645 which reintroduced the error.

This PR is a cherry-pick of the old PR mentioned above

NANASHI0X74 avatar Dec 28 '21 13:12 NANASHI0X74

The current implementation is still out of date, I think:

IO.prototype.join = () => this.unsafePerformIO();

From: https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch09

According to appendix_b (https://mostly-adequate.gitbook.io/mostly-adequate-guide/appendix_b), it should be:

IO.prototype.join = new IO(() => this.unsafePerformIO().unsafePerformIO());
I tested it myself and as far as I understand, it works:
#+begin_src js :noweb no-export
  <<js compose>>

  class IO {
    constructor(fn) {
      this.unsafePerformIO = fn
    }

    static of(val) {
      return new IO(() => val)
    }

    map(fn) {
      return new IO(compose(fn, this.unsafePerformIO))
    }

    join() {
      return new IO(() => this.unsafePerformIO().unsafePerformIO())
    }
  }

  const x = IO.of(123)
  const y = IO.of(x)
  const z = y.join()

  return {
    x,                          // IO(123)
    xperf: x.unsafePerformIO(), // 123

    y,                          // IO(IO(123))
    yperf: y.unsafePerformIO(), // IO(123)

    z,                          // IO(123)
    zperf: z.unsafePerformIO(), // 123
  }
#+end_src

#+RESULTS:
: {
:   x: IO { unsafePerformIO: [Function (anonymous)] },
:   xperf: 123,
:   y: IO { unsafePerformIO: [Function (anonymous)] },
:   yperf: IO { unsafePerformIO: [Function (anonymous)] },
:   z: IO { unsafePerformIO: [Function (anonymous)] },
:   zperf: 123
: }

sevillaarvin avatar Jul 23 '22 09:07 sevillaarvin