exploring-reasonml icon indicating copy to clipboard operation
exploring-reasonml copied to clipboard

Chapter: Functions

Open rauschma opened this issue 7 years ago • 6 comments

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

rauschma avatar Feb 07 '18 06:02 rauschma

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

vkammerer avatar Mar 08 '18 20:03 vkammerer

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.

rauschma avatar Mar 08 '18 21:03 rauschma

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).

vkammerer avatar Mar 08 '18 23:03 vkammerer

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.

tryangul avatar Mar 20 '18 17:03 tryangul

"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 avatar Nov 18 '18 20:11 nielsbom

"Compatibility of function types"

This part was unclear to me.

  • what is "compatibility of function types"?
  • why/when would I need "compatibility of function types"?
  • I'm not sure what the code example is trying to do, or what it is trying to show

nielsbom avatar Nov 18 '18 20:11 nielsbom