rauschma / exploring-reasonml

http://reasonmlhub.com/exploring-reasonml/
26 stars 0 forks source link

Chapter: Functions #9

Open rauschma opened 6 years ago

rauschma commented 6 years ago

http://reasonmlhub.com/exploring-reasonml/ch_functions.html

vkammerer commented 6 years ago

Hi Alex, thank you for the great book.

in your section about mutually recursive functions, you define even and odd as such:

let rec even = (x) =>
  if (x <= 0) {
    true
  } else {
    odd(x - 1)
  }
and odd = (x) => even(x - 1);

which makes them always return true (for ex, even(11) and odd(11) both return true).

the example could be rewritten as:

let rec even = x =>
  if (x === 0) {
    true;
  } else if (x === 1) {
    false;
  } else if (x < 0) {
    odd(1 - x);
  } else {
    odd(x - 1);
  }
and odd = x => even(x - 1);

but maybe it is too complex for a simple example

rauschma commented 6 years ago

Grrrr. This is the second time I got this function wrong.

I want these two functions to be mutually recursive. Therefore:

let rec even = (x) =>
  if (x <= 0) {
    true
  } else {
    odd(x - 1)
  }
and odd = (x) =>
  if (x <= 0) {
    false
  } else {
    even(x - 1)
  };

A more compact solution (that is not mutually recursive) is:

let rec even = (x) =>
  if (x <= 0) {
    true
  } else {
    !even(x - 1)
  };
let odd = (x) =>
  !even(x);

It’ll be fixed in the next release of the book.

vkammerer commented 6 years ago

If I'm not mistaken, your proposal here above is the third time ;)

Indeed your functions don't match the definitions of even and odd numbers, as they seem to imply that all negative integers are even. But there are also negative odd numbers (-1, -3 etc).

The function definitions I proposed are mutually recursive (even calls odd, and odd calls even).

tryangul commented 6 years ago

How does one read (pronounce) generic type annotations such as 'a and 'b in the example ListLabels.map: (~f: ('a) => 'b, list('a)) => list('b).

"Some type a/some type b", "prime a/prime b"?

I understand the concept, I would just like to be able to speak precisely about type signatures in the context of Reason.

nielsbom commented 5 years ago

"One nice feature of labels is that you can mention labeled parameters in any order:"

The mathematical operation demo'd in the function (addition) does not care about operand order. I think using minus or exponent would be a little more clear.

(doing an exponent of ints is not supported by "standard" Reason I found... so probably minus is easier)

nielsbom commented 5 years ago

"Compatibility of function types"

This part was unclear to me.