4 ms·
Because it would make a lot of code less nested and simpler to understand. The most common case is: if some_error_condition then None else (
by rwmj 12y ago
Because it would make a lot of code less nested and simpler to understand. The most common case is:
if some_error_condition then
None
else (
// everything else in the function is nested
)
which would be replaced with:
if some_error_condition then
return None;
// everything else is not nested
The situation is particularly bad when you have to do a lot of small tests at the beginning of your function. Think permissions checks:
let user_id =
match user with Some id -> id
| None ->
printf "you need to specify a user\n";
return None in
if not (permitted user_id) then
printf "this user is not permitted\n";
return None;
// go ahead and return Some object
The alternative is to use exceptions, either hidden within the function (requiring a nested function), or demanding that the caller is careful about catching exceptions. Exceptions are an unsafe back door, when what's really needed is a return statement.
- talex5 12y agoA style I sometimes see is people not indenting the normal code path of the match. So your example above would be written: match user with | None -> printf "you need to specify a user\n"; None | Some user_id when not (permitted user_id) -> printf "this user is not permitted\n"; None | Some user_id -> // go ahead and return Some object
- rwmj 12y agoStay classy, downvoters. You know I've been a working OCaml programmer for the last 12 years, using the language most days, so I do know a bit about the pain points.
- renox 12y agoSome people hates the 'return' keyword.. Suggest a '~' operator (like the ^ operator of Smalltalk) and your proposal will be better received ;-)
- Peaker 12y agoOriginal code: if some_error_condition then None else ( // everything else in the function is nested ) Why not use a Maybe/Either monad like: x <- some_maybe_value // everything else in the function isn't nested, and "x" is available (if some_maybe_value was Just) Kind of like exceptions, but a bit more explicit.