3 ms·
I thought this was a pretty great introduction. Part 2, in particular, finally helped me understand function type signatures in ML languages: the fact that, und
by girzel 8y ago
I thought this was a pretty great introduction. Part 2, in particular, finally helped me understand function type signatures in ML languages: the fact that, under the hood, functions only accept a single argument, and the way the type signatures are presented are merely an aesthetic cleanup of what it actually looks like (which would include more parentheses to indicate associativity).
One of the examples did refuse to compile for me, and I felt Part 1 was still too light on basic syntax. I tried to do the exercise at the end of Part 1, about prompting for, squaring, and printing an integer. This works:
let this_integer = read_int ()
let _ = print_int (this_integer * this_integer); print_newline ()
But this doesn't:
let this_integer = read_int () in
let _ = print_int (this_integer * this_integer); print_newline ()
And nothing in the tutorial explains why that should be so -- at least not that I could find.
I've also yet to see a really good explanation of when you need to use parentheses for grouping and when you don't -- this is the only part of the language that really feels like a "syntax error" to me. Like, "Look, ocaml is clean and doesn't need to use all this extraneous syntax! Except when it does."
Anyway, good introduction.
- nv-vn 8y agoSo the reason for this is actually because OCaml has 2 types of expressions, which is sort of confusing. The first is a top-level and the second is just a normal expression. In top-level expressions, they are implicitly put into scope. If you've seen any of the ";;" in tutorials, this indicates that you're working in the top-level (although these are pretty much always automatically inserted assuming you're not running a REPL). Now, if you're not in the top-level, you need to use the `let x = ... in ...` syntax, where the `in` is roughly analogous to a semi-colon. So the reason the first works is because the REPL runs at the top-level, and the second would only work inside of a function.
- girzel 8y agoOkay, I think I get it... And if you're not at top-level, ie you're in a function definition, you actually can't use "let" without an "in". That is a little weird, but not terrible. Thanks for the explanation.
- dmbaturin 8y agoThis would work: let _ = let this_integer = read_int () in print_int (this_integer * this_integer); print_newline () I agree part 1 should explain more of the basic syntax. The whole thing is a work in progress so I keep improving it as I get feedback.