exploring-reasonml
exploring-reasonml copied to clipboard
Chapter: Functions
http://reasonmlhub.com/exploring-reasonml/ch_functions.html
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
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.
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).
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.
"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)
"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