Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PureScript – Simple Multiline Computation

Consider the following JavaScript function, which performs a computation over several lines to clearly indicate the programmer’s intent:

function computation(first, second) {
  const a = first * first;
  const b = second - 4;
  const c = a + b;
  return c;
}

computation(12, 3)
//143

computation(-3, 2.6)
//7.6

I have tried using do notation to solve this with PureScript but I seem to be just short of understanding some key concept. The do notation examples in the documentation only covers do notation when the value being bound is an array (https://book.purescript.org/chapter4.html#do-notation), but in my example I would like the values to be simple values of the Int or Number type.

While it is possible to perform this computation in one line, it makes the code harder to debug and does not scale to many operations.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would the computation method be written correctly in PureScript so that…

  1. If computation involved 1000 intermediate steps, instead of 3, the code would not suffer from excessive indenting but would be as readable as possible

  2. Each step of the computation is on its own line, so that, for example, the code could be reviewed line by line by a supervisor, etc., for quality

>Solution :

You don’t need the do notation. The do notation is intended for computations happening in a monad, whereas your computation is naked.

To define some intermediate values before returning result, use the let .. in construct:

computation first second =
  let a = first * first
      b = second - 4
      c = a + b
  in c

But if you really want to use do, you can do that as well: it also supports naked computations just to give you some choice. The difference is that within a do you can have multiple lets on the same level (and they work the same as one let with multiple definitions) and you don’t need an in:

computation first second = do
  let a = first * first -- first let
      b = second - 4
  let c = a + b         -- second let
  c                     -- no in
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading